Let's say I have a dataframe
micolumns = pd.MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'),
('b', 'foo'), ('b', 'bah')])
miindex=np.arange(3)
dfmi = pd.DataFrame(np.arange(3 * len(micolumns)).reshape((len(miindex), len(micolumns))),
index=miindex, columns=micolumns).sort_index().sort_index(axis=1)
a b
bar foo bah foo
0 1 0 3 2
1 5 4 7 6
2 9 8 11 10
And I want to add prefix to column at level zero, how can I do that?
Currently I'm renaming the columns like below, and it feels redundant.
df_new = dfmi.rename(columns=dict(zip(dfmi.columns.levels[0],'pre_'+dfmi.columns.levels[0])),level=0)
pre_a pre_b
bar foo bah foo
0 1 0 3 2
1 5 4 7 6
2 9 8 11 10
There is no level parameter for add_prefix
function. Is there any similar function for that?
One quick away is:
dfmi.columns = pd.MultiIndex.from_tuples([(f'pre_{a}',b) for a,b in dfmi.columns])
or rename
with mapper
:
dfmi.rename(mapper=lambda x: f'pre_{x}',
axis='columns',
level=0,
inplace=True)
An unusual way would be:
dfmi.stack(level=1).add_prefix('pre_').unstack().dropna(how='all',axis=1)
pre_a pre_b
bar foo bah foo
0 1.0 0.0 3.0 2.0
1 5.0 4.0 7.0 6.0
2 9.0 8.0 11.0 10.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With