0

Is there another more elegant way to perform this (input=df, desired output=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 Answer 1

1

IIUC , it is pivot not 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  
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, finally I did this, that I imagine is more or less the same pt=df.pivot_table(values='value',index='y',columns='m')
@RaulMuñoz yep pivot is alternative way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.