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)'
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 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.
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.
Solved:
df.drop('c', axis=1, level=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