分组大熊猫数据帧的平均值

时间:2017-08-23 12:19:10

标签: python pandas dataframe group-by

我需要计算每天的colums持续时间和km的平均值 值== 1且值为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

如何修改此解决方案以获得持续时间duration_value0,duration_value1,km_value0和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

2 个答案:

答案 0 :(得分:2)

我认为按Date以及value进行分组应该这样做。 拨打dfGroupBy.mean,然后拨打df.reset_index以获得所需的输出:

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

答案 1 :(得分:1)

我认为你正在寻找支点表,即

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

输出:

           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]:

如果你想要新的列名如distance0,distance1 ......你可以使用列表理解,即如果你将数据透视表存储在ndf

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

输出:

            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