neanderslob
neanderslob

Reputation: 2703

Rename multiindex headers in one column only

I'm trying to change the subcolumn headers of a multiindex dataframe. The trick is that I'm only trying to change the headers under one of the supercolumns. See below

Given:

df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))

I want to change the column header b to j BUT ONLY under column a; I want the headers under column d to remain unchanged.

If I wanted all columns b to be changed I'd do the following

df.rename(columns={'b': 'j'}, level=1)

How can I specifiy the super column under which to change the subcolumn headings?

Upvotes: 0

Views: 254

Answers (3)

akuiper
akuiper

Reputation: 215117

You can map over column names and check if the index is ('a', 'b') and replace b with j if it matches:

df.columns = df.columns.map(lambda x: ('a', 'j') if x == ('a', 'b') else x)

df    
#     a         d     
#     j    c    b    c
#0    1    2    3    4
#1   10   20   30   40
#2  100  200  300  400

Upvotes: 4

Pygirl
Pygirl

Reputation: 13349

You can try this: (not so good but works)

df.columns = pd.MultiIndex.from_tuples([(x,'j') if (x=='a' and y=='b') else (x,y) for x,y in df.columns])

Upvotes: 1

osint_alex
osint_alex

Reputation: 1022

I think this does it?

import pandas as pd

df = pd.DataFrame([[1,2,3,4], [10,20,30,40], [100,200,300,400]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
     a         d     
     b    c    b    c
0    1    2    3    4
1   10   20   30   40
2  100  200  300  400

Now rename the columns:

df.columns = pd.MultiIndex.from_tuples((("a", "j"), ("a", "c"), ("d", "b"), ("d", "c")))
print(df)
     a         d     
     j    c    b    c
0    1    2    3    4
1   10   20   30   40
2  100  200  300  400

Upvotes: 0

Related Questions