[英]Pandas dataframe, how can I group by multiple columns and apply sum for specific column and add new count column?
[英]How to get sum and count of specific column in pandas?
我的 dataframe 看起来像这样:
df = pd.DataFrame({'percent':[0.5, 0.2, -0.2, 0.5 ],
'amt':[10, 5, -5, 10]})
percent amt
0.5 10
0.2 5
-0.2 -5
0.5 10
我想获取百分比为“>0”、百分比为“<0”的行数和金额列的总和。
期望的结果
percentage '>0' = 3
percentage '<0' = 1
amt = 20
我试过了
df[df.percent > 0].count()
df[df.percent < 0].count()
df['amt'].sum()
但这是返回其他东西,而不是我想要的单个值的结果。
这应该工作
print(df[df['percent']>0].shape[0]) #Rows with % > 0
print(df[df['percent']<0].shape[0]) #Rows with % < 0
print(df['amt'].sum()) #Sum of amount
Output:
3
1
20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.