在python中使用groupby对数据进行分组

时间:2018-04-29 14:58:54

标签: python pandas grouping

还有另一种更优雅的方式来执行此操作(输入= df,所需输出= dfc)?:

import pandas as pd 
import numpy as np

df=pd.DataFrame({'date': pd.date_range(start='2016-01-01',
                         periods=48,freq='M'),'value': 
np.random.normal(size=48)}).set_index('date')

df['m']=df.index.month
df['y']=df.index.year
df.index=df['y']
gd=df.groupby(['m'])['value']

for i,g in enumerate(gd): 
    if i==0:
        dfc=gd.get_group(i+1)
    else:
        dfc=pd.concat([dfc,gd.get_group(i+1)],axis=1)
dfc.columns=['jan','feb','march','april','may','june','july','aug','sept','oct','nov','dec']

1 个答案:

答案 0 :(得分:1)

IIUC,pivot groupby

df.set_index('m',append=True).value.unstack()
Out[363]: 
m           1         2         3         4         5         6         7   \
y                                                                            
2016 -0.894336 -1.079922  1.265373 -0.448711  0.052372  0.212654 -0.663333   
2017 -0.120984  0.208169 -0.783443 -0.654959 -1.265553 -0.006452  0.201900   
2018 -0.446728 -0.454516  0.128904  0.357648 -0.222810 -1.435976  0.372455   
2019  0.540930 -0.376506 -0.246701  0.307713  0.806210  0.282931 -0.573333   
m           8         9         10        11        12  
y                                                       
2016 -2.666931  0.946312 -0.857844  0.518656 -0.025353  
2017 -0.775419  0.822879 -1.471175 -0.690260  0.810011  
2018  0.381087  0.960885  2.324242  0.509771 -1.157182  
2019  0.634233  1.194121  1.000851  1.301358  0.328702