pandas dataframe groupby: sum/count of only positive numbers
pandas, python
Solution
Not as elegant as above, but deals differently some corner cases. `df` stands for `frame` from original question.
>>> 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
Problem
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]) ```