The purpose of this post is to understand how to add a column to a level in a MultiIndex.DataFrame
using apply()
and shift()
<
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
T
to get a picture that would easily fitthere 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)