繁体   English   中英

根据熊猫数据框中的另一列值计算值的总和?

[英]Calculate the sum of values based on another column value in pandas dataframe?

示例数据框

country   result    name  
  UK        3       created
  US        5       created
  UK        7       created
  India     4       completed
  India     6       created
  US        1       completed

预期产出

country   result    name  
  UK        3       created
  US        5       created
  UK        7       created
  India     4       completed
  India     6       created
  US        1       completed
  UK        10      pending       
  US        6       pending
  India     10      pending

我需要在每个国家/地区添加创建和完成的结果,它应该有一个名为“待定”的名称

您可以尝试groupby.sum然后pd.concat

out = df.groupby('country', as_index=False)['result'].sum()
out['name'] = 'pending'
out = pd.concat([df, out], ignore_index=True)
print(out)

  country  result       name
0      UK       3    created
1      US       5    created
2      UK       7    created
3   India       4  completed
4   India       6    created
5      US       1  completed
6   India      10    pending
7      UK      10    pending
8      US       6    pending

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM