如何在 pandas 中复制相同行但在列中具有不同信息?

huangapple go评论61阅读模式
英文:

How can I duplicate the same row but with different information in a column in pandas?

问题

这是您的代码部分的翻译:

我的pandas数据框如下所示

```python
import pandas as pd 
table = pd.DataFrame({'Range': ["A", "B", "C", "A"], 'First Name': ["W","X","Y", "Z"], 'ID': [1,2,3,4]})

我想要复制相同的行,如果在"Level"列中有文本"A",则在"Activity"列中添加文本"Monitoring"和"Informant",类似于这样:

我尝试使用以下代码进行复制:

columns_new = pd.DataFrame(columns=["NO ID","Level", "Name", "Activity"])

row_modified = []

for index, row in table.iterrows():
    rang = row['Range']
    f_name= row['First Name']
    n_id = row['ID']

    columns_new.loc[index, "NO ID"] = n_id
    columns_new.loc[index, "Level"] = rang
    columns_new.loc[index, "Name"] = f_name

    if  rang == "A":
        row_modified.append(row)
        row_modified.append(row)
    else:
        row_modified.append(row)

column_new2 = pd.DataFrame(row_modified)
column_new2

但我不知道如何添加我想要的文本 😅


如果您需要进一步的帮助或有其他问题,请随时告诉我。

<details>
<summary>英文:</summary>

My pandas dataframe looks like this:

import pandas as pd
table = pd.DataFrame({'Range': ["A", "B", "C", "A"],'First Name': ["W","X","Y", "Z"], 'ID': [1,2,3,4]})


![Initial state of dataframe](https://i.stack.imgur.com/XxQ5V.png)

I want to replicate the same row if in the &quot;Level&quot; column I have the text &quot;A&quot;, but in the &quot;Activity&quot; column add the text &quot;Monitoring&quot; and &quot;Informant&quot;, something like this:

![Desired output of data transformation example](https://i.stack.imgur.com/XXUbN.png)

I tried to make the duplicate with this code

columns_new = pd.DataFrame(columns=["NO ID","Level", "Name", "Activity"])

row_modified = []

for index, row in table.iterrows():
rang = row['Range']
f_name= row['First Name']
n_id = row['ID']

columns_new.loc[index, "NO ID"] = n_id
columns_new.loc[index, "Level"] = rang
columns_new.loc[index, "Name"] = f_name

if  rang == &quot;A&quot;:
    row_modified.append(row)
    row_modified.append(row)
else:
	row_modified.append(row)

column_new2 = pd.DataFrame(row_modified)
column_new2


![Dataframe result of code so far](https://i.stack.imgur.com/TSbpE.png)

But I don&#39;t know how to add the texts I want &#128517;

</details>


# 答案1
**得分**: 2

你可以使用 [`merge`](https://pandas.pydata.org/docs/reference/api/pandas.merge.html) 函数:

```python
s = pd.Series(['Monitoring', 'Informant'], index=['A', 'A'], name='Activity')

(table.merge(s, left_on='Range', right_index=True, how='left')
      .fillna({'Activity': 'Assistant'})
)

输出结果:

  Range First Name  ID    Activity
0     A          W   1  Monitoring
0     A          W   1   Informant
1     B          X   2   Assistant
2     C          Y   3   Assistant
3     A          Z   4  Monitoring
3     A          Z   4   Informant
英文:

You can use a merge:

s = pd.Series([&#39;Monitoring&#39;, &#39;Informant&#39;], index=[&#39;A&#39;, &#39;A&#39;], name=&#39;Activity&#39;)

(table.merge(s, left_on=&#39;Range&#39;, right_index=True, how=&#39;left&#39;)
      .fillna({&#39;Activity&#39;: &#39;Assistant&#39;})
)

Output:

  Range First Name  ID    Activity
0     A          W   1  Monitoring
0     A          W   1   Informant
1     B          X   2   Assistant
2     C          Y   3   Assistant
3     A          Z   4  Monitoring
3     A          Z   4   Informant

答案2

得分: 1

你可以使用一个映射字典:

d = {'A': ['监控', '通知者']}

out = (table.assign(活动=table['范围'].map(d).fillna('助手'))
            .explode('活动'))
print(out)

# 输出结果
  范围 姓   ID 活动
0     A   W  1 监控
0     A   W  1 通知者
1     B   X  2 助手
2     C   Y  3 助手
3     A   Z  4 监控
3     A   Z  4 通知者
英文:

You can use a mapping dict:

d = {&#39;A&#39;: [&#39;Monitoring&#39;, &#39;Informant&#39;]}

out = (table.assign(Activity=table[&#39;Range&#39;].map(d).fillna(&#39;Assistant&#39;))
            .explode(&#39;Activity&#39;))
print(out)

# Output
  Range First Name  ID    Activity
0     A          W   1  Monitoring
0     A          W   1   Informant
1     B          X   2   Assistant
2     C          Y   3   Assistant
3     A          Z   4  Monitoring
3     A          Z   4   Informant

huangapple
  • 本文由 发表于 2023年2月27日 02:47:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定