Skip to content Skip to sidebar Skip to footer

Adding And Renaming A Column In A Multiindex Dataframe

The purpose of this post is to understand how to add a column to a level in a MultiIndex.DataFrame using apply() and shift() Create the DataFrame import pandas as pd df = pd.DataF

Solution 1:

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

enter image description here

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

defmap_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 inenumerate(index.levels)], inplace=True)
dct = {'amount':'daily_added_value'}
map_level(dav.T, dct, level=2)

Post a Comment for "Adding And Renaming A Column In A Multiindex Dataframe"