Mean of a grouped-by pandas dataframe

末鹿安然 提交于 2019-12-11 06:43:57

问题


I need to calculate the mean per day of the colums duration and km for the rows with value ==1 and values = 0.

df
Out[20]: 
                          Date duration km   value
0   2015-03-28 09:07:00.800001    0      0    0
1   2015-03-28 09:36:01.819998    1      2    1
2   2015-03-30 09:36:06.839997    1      3    1 
3   2015-03-30 09:37:27.659997    nan    5    0 
4   2015-04-22 09:51:40.440003    3      7    0
5   2015-04-23 10:15:25.080002    0      nan  1

how can I modify this solution in order to have the means duration_value0, duration_value1, km_value0 and km_value1?

df = df.set_index('Date').groupby(pd.Grouper(freq='d')).mean().dropna(how='all')
print (df)
            duration   km
Date                     
2015-03-28       0.5  1.0
2015-03-30       1.5  4.0
2015-04-22       3.0  7.0
2015-04-23       0.0  0.0

回答1:


I think you are looking pivot table i.e

df.pivot_table(values=['duration','km'],columns=['value'],index=df['Date'].dt.date,aggfunc='mean')

Output:

           duration        km     
value             0    1    0    1
Date                              
2015-03-28      0.0  1.0  0.0  2.0
2015-03-30      NaN  1.0  5.0  3.0
2015-04-22      3.0  NaN  7.0  NaN
2015-04-23      NaN  0.0  NaN  NaN
In [24]:

If you want the new column names like distance0,distance1 ... You can use list comprehension i.e if you store the pivot table in ndf

ndf.columns = [i[0]+str(i[1]) for i in ndf.columns]

Output:

            duration0  duration1  km0  km1
Date                                      
2015-03-28        0.0        1.0  0.0  2.0
2015-03-30        NaN        1.0  5.0  3.0
2015-04-22        3.0        NaN  7.0  NaN
2015-04-23        NaN        0.0  NaN  NaN




回答2:


I believe doing a group by Date as well as value should do it. Call dfGroupBy.mean followed by df.reset_index to get your desired output:

In [713]: df.set_index('Date')\
           .groupby([pd.Grouper(freq='d'), 'value'])\
           .mean().reset_index(1, drop=True)
Out[713]: 
            duration   km
Date                     
2015-03-28       0.0  0.0
2015-03-28       1.0  2.0
2015-03-30       NaN  5.0
2015-03-30       1.0  3.0
2015-04-22       3.0  7.0
2015-04-23       0.0  NaN


来源:https://stackoverflow.com/questions/45839539/mean-of-a-grouped-by-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!