Adding and Renaming a Column in a Multiindex DataFrame

前端 未结 1 932
小蘑菇
小蘑菇 2021-01-14 18:44

The purpose of this post is to understand how to add a column to a level in a MultiIndex.DataFrame using apply() and shift()

<

1条回答
  •  野的像风
    2021-01-14 19:13

    Skip the groupby it is not necessary

    amount = df.loc[:, pd.IndexSlice[:, :, 'amount']]
    inject = df.loc[:, pd.IndexSlice[:, :, 'injection']]
    dav = amount - amount.shift() - inject.shift().values
    #dav.columns.set_levels(['daily_added_value'], level=2, inplace=True)
    
    pd.concat([df, dav], axis=1).sort_index(axis=1).T
    

    Note: I used T to get a picture that would easily fit

    there appears to be a bug in set_levels and as such it is not advised to use it.

    Workaround to rename the MultiIndex Column in the DataFrame dav

    def map_level(df, dct, level=2):
        index = df.index
        index.set_levels([[dct.get(item, item) for item in names] if i==level else    names
                           for i, names in enumerate(index.levels)], inplace=True)
    dct = {'amount':'daily_added_value'}
    map_level(dav.T, dct, level=2)
    

    0 讨论(0)
提交回复
热议问题