[英]pandas dataframe groupby: sum/count of only positive numbers
I have a dataframe ('frame') on which I want to aggregate by Country and Date: 我有一个数据框('框架'),我想按国家和日期聚合:
aggregated=pd.DataFrame(frame.groupby(['Country','Date']).CaseID.count())
aggregated["Total duration"]=frame.groupby(['Country','Date']).Hours.sum()
aggregated["Mean duration"]=frame.groupby(['Country','Date']).Hours.mean()
I want to compute the above figures (total duration, mean duration, etc.) only for the positive 'Hours' numbers in 'frame'. 我想计算上述数字(总持续时间,平均持续时间等)仅针对'框架'中的正'小时'数字。 How can I do that?
我怎样才能做到这一点?
Thanks! 谢谢!
Sample "frame" 样本“框架”
import pandas as pd
Line1 = {"Country": "USA", "Date":"01 jan", "Hours":4}
Line2 = {"Country": "USA", "Date":"01 jan", "Hours":3}
Line3 = {"Country": "USA", "Date":"01 jan", "Hours":-999}
Line4 = {"Country": "Japan", "Date":"01 jan", "Hours":3}
pd.DataFrame([Line1,Line2,Line3,Line4])
怎么样 -
frame[frame["Hours"] > 0].groupby(['Country','Date'])
Not as elegant as above, but deals differently some corner cases. 不像上面那么优雅,但处理不同的角落案例。
df
stands for frame
from original question. df
代表原始问题的frame
。
>>> df.groupby(['Country','Date']).agg(lambda x: x[x>0].mean())
Hours
Country Date
Japan 01 jan 3.0
USA 01 jan 3.5
>>> df.ix[3, 'Hours'] = -1
>>> df.groupby(['Country','Date']).agg(lambda x: x[x>0].mean())
Hours
Country Date
Japan 01 jan NaN
USA 01 jan 3.5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.