Removing one (sub) column from MultiIndex

I have the following data file df

    col1        col2        col3
    a     b     a     b     a     b       
1   ...
2
3

and just can't figure out how to remove only one β€œsublevel”, for example. df.col1.a

I can df.col1.drop('a', axis=1), but reassign it as df.col1=df.col1.drop('a', axis=1)it fails.

The logical structure df.columsI understand, but how to change it?

+4
source share
1 answer

Drop is a very flexible method, and it can be used in several ways:

In [11]: mi = pd.MultiIndex.from_product([['col1', 'col2', 'col3'], ['a', 'b']])

In [12]: df = pd.DataFrame(1, index=[0], columns=mi)

In [13]: df
Out[13]:
   col1     col2     col3
      a  b     a  b     a  b
0     1  1     1  1     1  1

Drop one column using a tuple:

In [14]: df.drop(('col1', 'a'), axis=1)
Out[14]:
   col1  col2     col3
      b     a  b     a  b
0     1     1  1     1  1

or a list using a list of tuples:

In [15]: df.drop([('col1', 'a'), ('col2', 'b')], axis=1)
Out[15]:
   col1  col2  col3
      b     a     a  b
0     1     1     1  1

or through a level, for example. all as:

In [16]: df.drop('a', level=1, axis=1)
Out[16]:
   col1  col2  col3
      b     b     b
0     1     1     1

At 0.14, you can also pass in the regular expression of what needs to be removed ...

/:

In [21]: df.columns.droplevel(1)
Out[21]: Index([u'col1', u'col1', u'col2', u'col2', u'col3', u'col3'], dtype='object')
+5

Source: https://habr.com/ru/post/1531705/


All Articles