Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: drop a level from a multi-level column index?

Tags:

python

pandas

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 
like image 296
David Wolever Avatar asked Mar 06 '14 18:03

David Wolever


People also ask

How do I drop a multi-level column in Pandas?

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.

How do I delete a level on Pandas?

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.


1 Answers

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] 
like image 171
DSM Avatar answered Sep 21 '22 23:09

DSM