applying several functions in transform in pandas

后端 未结 3 733
执念已碎
执念已碎 2021-01-14 10:17

After a groupby, when using agg, if a dict of columns:functions is passed, the functions will be applied in the corresponding columns.

3条回答
  •  -上瘾入骨i
    2021-01-14 11:15

    You can still use a dict but with a bit of hack:

    df_test.groupby('a').transform(lambda x: {'b': x.cumsum(), 'c': x.cumprod()}[x.name])
    Out[427]: 
        b     c
    0   2     3
    1  22    90
    2  30    50
    3  24  2970
    4  34  2500
    

    If you need to keep column a, you can do:

    df_test.set_index('a')\
           .groupby('a')\
           .transform(lambda x: {'b': x.cumsum(), 'c': x.cumprod()}[x.name])\
           .reset_index()
    Out[429]: 
       a   b     c
    0  1   2     3
    1  1  22    90
    2  2  30    50
    3  1  24  2970
    4  2  34  2500
    

    Another way is to use an if else to check column names:

    df_test.set_index('a')\
           .groupby('a')\
           .transform(lambda x: x.cumsum() if x.name=='b' else x.cumprod())\
           .reset_index()
    

提交回复
热议问题