Home > front end >  Apply pct_change at group level to multiple value columns
Apply pct_change at group level to multiple value columns

Time:03-01

I want to do a pct_change() at group level and I can get one value column done. But I am wondering how to do it at multiple value columns and bring them back to the dataframe with a prefix name like pc_.

df1 = (
    pd.DataFrame(index=[
    pd.date_range(start='1900', periods=100, freq='Y'),
    ['AA']*25   ['BB']*25   ['AA']*25   ['BB']*25], 
    columns=['kit', 'kot', 'lou', 'sit', 'mok', 'jdf'], data=np.random.random(size=(100, 6)))
    .reset_index()
    .rename(columns = {"level_0":"date", "level_1":"id"})
); df1

         date  id         kit         kot         lou         sit         mok         jdf
0  1900-12-31  AA 0.864240371 0.659370174 0.229252996 0.981720569 0.394823210 0.434585043
1  1901-12-31  AA 0.502068634 0.793725096 0.320513065 0.237001280 0.828018026 0.765368720
2  1902-12-31  AA 0.039982207 0.640912468 0.340945764 0.126530005 0.723968491 0.129242304
3  1903-12-31  AA 0.399179469 0.880042770 0.425164461 0.000570785 0.177299390 0.464887687
4  1904-12-31  AA 0.336595884 0.894579761 0.426959720 0.722896852 0.648829366 0.487376511
..        ...  ..         ...         ...         ...         ...         ...         ...
95 1995-12-31  BB 0.081561967 0.920471123 0.038710265 0.570420698 0.897624426 0.519158508
96 1996-12-31  BB 0.908299660 0.935711302 0.616107778 0.823604311 0.042485213 0.144239769
97 1997-12-31  BB 0.966595578 0.028803886 0.719747720 0.277754872 0.119475544 0.412695856
98 1998-12-31  BB 0.779183450 0.568281590 0.129776943 0.183239231 0.399786356 0.903425318
99 1999-12-31  BB 0.801225084 0.263635627 0.146833075 0.951690764 0.807731210 0.512193069

CodePudding user response:

IIUC, use add_prefix and join:

df1.join(df1.drop('date', axis=1).groupby('id').pct_change().add_prefix('pc_'))

output:

         date  id       kit       kot       lou       sit       mok       jdf     pc_kit     pc_kot       pc_lou     pc_sit       pc_mok      pc_jdf
0  1900-12-31  AA  0.417022  0.720324  0.000114  0.302333  0.146756  0.092339        NaN        NaN          NaN        NaN          NaN         NaN
1  1901-12-31  AA  0.186260  0.345561  0.396767  0.538817  0.419195  0.685220  -0.553356  -0.520271  3468.010779   0.782199     1.856407    6.420727
2  1902-12-31  AA  0.204452  0.878117  0.027388  0.670468  0.417305  0.558690   0.097670   1.541138    -0.930973   0.244333    -0.004508   -0.184656
3  1903-12-31  AA  0.140387  0.198101  0.800745  0.968262  0.313424  0.692323  -0.313351  -0.774402    28.237493   0.444159    -0.248932    0.239190
...
  • Related