Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a multi level column table like this:

    a    ---+---+---     b | c | f --+---+---+--- 0 | 1 | 2 | 7 1 | 3 | 4 | 9 

How can I drop column "c" by name? to look like this:

    a    ---+---     b | f --+---+--- 0 | 1 | 7 1 | 3 | 9 

I tried this:

del df['c'] 

but I get the following error, which makes sense:

KeyError: 'Key length (1) was greater than MultiIndex lexsort depth (0)'

like image 337
Boosted_d16 Avatar asked Aug 05 '14 09:08

Boosted_d16


People also ask

How do I drop a column with multiple indexes?

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 you drop a column level?

To drop a level from a multi-level column index, use the columns. droplevel(). We have used the Multiindex. from_tuples() is used to create indexes column-wise.

How do I drop a column with an index?

You can drop columns by index by using DataFrame. drop() method and by using DataFrame. iloc[]. columns property to get the column names by index.


1 Answers

Solved:

df.drop('c', axis=1, level=1) 
like image 142
Boosted_d16 Avatar answered Sep 22 '22 13:09

Boosted_d16