[英]Calculate the sum of values based on another column value in pandas dataframe?
Sample dataframe示例数据框
country result name
UK 3 created
US 5 created
UK 7 created
India 4 completed
India 6 created
US 1 completed
Expected output预期产出
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
I need to add the created and completed result on each country and it should have a name called "pending"我需要在每个国家/地区添加创建和完成的结果,它应该有一个名为“待定”的名称
You can try groupby.sum
then pd.concat
您可以尝试
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.