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
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
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