Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add prefix to multi index columns at particular level?

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?

like image 399
Bharath Avatar asked Aug 31 '19 17:08

Bharath


2 Answers

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)
like image 124
Quang Hoang Avatar answered Sep 19 '22 01:09

Quang Hoang


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
like image 30
anky Avatar answered Sep 19 '22 01:09

anky