Inplace transformation pandas with groupby

后端 未结 2 996
孤街浪徒
孤街浪徒 2020-12-21 08:20

Would it be possible to mutate DataFrame inplace with groupby statement?

import pandas as pd
dt = pd.DataFrame({
                       


        
2条回答
  •  伪装坚强ぢ
    2020-12-21 09:07

    I'm quite sure you can't mutate the dataframe during a group by. You can do exactly the same operation mapping every lettering with it's mean and then perform the operation.

    df['NEW_COL'] = df['VALUE'] - df['LETTER'].map(dt.groupby("LETTER")['VALUE'].mean()).values
    

    This will deal with any possible ordering issue, which I wouldn't trust to be guarantee even if tested. Better safe than sorry :)

    Also, I'm using .values accessor after the map because I'm not sure what the index of the "mapped" series will be the same of the 'VALUE' series, which sometime will result with NaN.

提交回复
热议问题