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

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

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

问题

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

  1. 我的pandas数据框如下所示
  2. ```python
  3. import pandas as pd
  4. table = pd.DataFrame({'Range': ["A", "B", "C", "A"], 'First Name': ["W","X","Y", "Z"], 'ID': [1,2,3,4]})

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

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

  1. columns_new = pd.DataFrame(columns=["NO ID","Level", "Name", "Activity"])
  2. row_modified = []
  3. for index, row in table.iterrows():
  4. rang = row['Range']
  5. f_name= row['First Name']
  6. n_id = row['ID']
  7. columns_new.loc[index, "NO ID"] = n_id
  8. columns_new.loc[index, "Level"] = rang
  9. columns_new.loc[index, "Name"] = f_name
  10. if rang == "A":
  11. row_modified.append(row)
  12. row_modified.append(row)
  13. else:
  14. row_modified.append(row)
  15. column_new2 = pd.DataFrame(row_modified)
  16. column_new2

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

  1. 如果您需要进一步的帮助或有其他问题,请随时告诉我。
  2. <details>
  3. <summary>英文:</summary>
  4. 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]})

  1. ![Initial state of dataframe](https://i.stack.imgur.com/XxQ5V.png)
  2. 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:
  3. ![Desired output of data transformation example](https://i.stack.imgur.com/XXUbN.png)
  4. 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

  1. if rang == &quot;A&quot;:
  2. row_modified.append(row)
  3. row_modified.append(row)
  4. else:
  5. row_modified.append(row)

column_new2 = pd.DataFrame(row_modified)
column_new2

  1. ![Dataframe result of code so far](https://i.stack.imgur.com/TSbpE.png)
  2. But I don&#39;t know how to add the texts I want &#128517;
  3. </details>
  4. # 答案1
  5. **得分**: 2
  6. 你可以使用 [`merge`](https://pandas.pydata.org/docs/reference/api/pandas.merge.html) 函数:
  7. ```python
  8. s = pd.Series(['Monitoring', 'Informant'], index=['A', 'A'], name='Activity')
  9. (table.merge(s, left_on='Range', right_index=True, how='left')
  10. .fillna({'Activity': 'Assistant'})
  11. )

输出结果:

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

You can use a merge:

  1. s = pd.Series([&#39;Monitoring&#39;, &#39;Informant&#39;], index=[&#39;A&#39;, &#39;A&#39;], name=&#39;Activity&#39;)
  2. (table.merge(s, left_on=&#39;Range&#39;, right_index=True, how=&#39;left&#39;)
  3. .fillna({&#39;Activity&#39;: &#39;Assistant&#39;})
  4. )

Output:

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

答案2

得分: 1

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

  1. d = {'A': ['监控', '通知者']}
  2. out = (table.assign(活动=table['范围'].map(d).fillna('助手'))
  3. .explode('活动'))
  4. print(out)
  5. # 输出结果
  6. 范围 ID 活动
  7. 0 A W 1 监控
  8. 0 A W 1 通知者
  9. 1 B X 2 助手
  10. 2 C Y 3 助手
  11. 3 A Z 4 监控
  12. 3 A Z 4 通知者
英文:

You can use a mapping dict:

  1. d = {&#39;A&#39;: [&#39;Monitoring&#39;, &#39;Informant&#39;]}
  2. out = (table.assign(Activity=table[&#39;Range&#39;].map(d).fillna(&#39;Assistant&#39;))
  3. .explode(&#39;Activity&#39;))
  4. print(out)
  5. # Output
  6. Range First Name ID Activity
  7. 0 A W 1 Monitoring
  8. 0 A W 1 Informant
  9. 1 B X 2 Assistant
  10. 2 C Y 3 Assistant
  11. 3 A Z 4 Monitoring
  12. 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:

确定