If I've got a multi-level column index:
>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> pd.DataFrame([[1,2], [3,4]], columns=cols)
a ---+-- b | c --+---+-- 0 | 1 | 2 1 | 3 | 4
How can I drop the "a" level of that index, so I end up with:
b | c --+---+-- 0 | 1 | 2 1 | 3 | 4
To drop multiple levels from a multi-level column index, use the columns. droplevel() repeatedly. We have used the Multiindex. from_tuples() is used to create indexes column-wise.
To remove a level using the name of the level and return the index, use the multiIndex. droplevel() method in Pandas. Set the name of the level to be removed as parameter.
You can use MultiIndex.droplevel
:
>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")]) >>> df = pd.DataFrame([[1,2], [3,4]], columns=cols) >>> df a b c 0 1 2 1 3 4 [2 rows x 2 columns] >>> df.columns = df.columns.droplevel() >>> df b c 0 1 2 1 3 4 [2 rows x 2 columns]
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