Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a second level column header/index to dataframe by matching to dictionary values?

I have an existing dataframe.

l1 | a    b    c  |  d    e    f
--------------------------------
0  | 1    1    1  |  1    1    1
1  | 1    1    1  |  1    1    1
2  | 1    1    1  |  1    1    1

And this dictionary.

{
  "a": "dog",
  "b": "dog",
  "c": "dog",
  "d": "fish",
  "e": "fish",
  "f": "fish",
}

What is the simplest way to create a second column level matching the existing columns to their category from the dictionary?

The real columns and dictionary are much bigger and less organized. 🙃

The result should look like this.

l2 |     dog      |     fish
l1 | a    b    c  |  d    e    f
--------------------------------
0  | 1    1    1  |  1    1    1
1  | 1    1    1  |  1    1    1
2  | 1    1    1  |  1    1    1
like image 860
GollyJer Avatar asked Dec 15 '25 05:12

GollyJer


1 Answers

Add an extra mapping for the first series, then use pd.MultiIndex.from_tuples:

d.update({'l1': 'l2'})
df.columns = pd.MultiIndex.from_tuples([(d[k], k) for k in df.columns])

print(df)

  l2 dog       fish      
  l1   a  b  c    d  e  f
0  0   1  1  1    1  1  1
1  1   1  1  1    1  1  1
2  2   1  1  1    1  1  1
like image 196
jpp Avatar answered Dec 16 '25 19:12

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!