【问题标题】:Summing and saving the values of column based on other column pandas [duplicate]根据其他列熊猫求和并保存列的值[重复]
【发布时间】:2019-09-09 15:39:55
【问题描述】:

df1 =

A        B
61880    7
62646    8
62651    9
62656    10
62783    11
61880    3
62646    2

我想做data.groupby('A')['B'].sum(),但要根据“A”的值将“B”的结果保存为新列“B_updated”

data.groupby('A')['B'].sum() 之后我的输出是:

A        B
61880    10
62646    10
...

很好,但我无法执行进一步的操作。因此,我想保存“B”wrt“A”。因为我接下来的操作是Math operations of column based on same values of other column pandas

【问题讨论】:

  • 你的意思是df['B_updated']=df.groupby('A')['B'].transform('sum') ??
  • 你能发布想要的输出吗?还是你只需要data.groupby('A')['B'].sum().reset_index()
  • @NazarTarlanli:您是设置列还是只运行 anky_91 解决方案的右侧?索引将如您所愿匹配。
  • @anky_91 ,看起来不错!我需要检查并在评论中告知!谢谢!
  • @fuglede,是的!我有点困惑。似乎一切正常!我现在正在检查

标签: python pandas dataframe


【解决方案1】:

试试这个:

x_df = df.groupby('A').size().reset_index(name='B_updated')
print(x_df)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2020-11-12
    • 2019-07-25
    • 1970-01-01
    • 2018-10-26
    • 2018-11-08
    • 2020-04-09
    • 2023-01-26
    相关资源
    最近更新 更多