从MultiIndex中删除单个(子)列 [英] Dropping a single (sub-) column from a MultiIndex

查看:979
本文介绍了从MultiIndex中删除单个(子)列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框 df

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

并且无法弄清楚如何只丢弃一个'sublevel',例如 df.col1.a

and just cannot figure out how to drop only a single 'sublevel', e.g. df.col1.a

我可以 df.col1.drop('a' ,axis = 1),但重新分配,如 df.col1 = df.col1.drop('a',axis = 1)失败。

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

逻辑结构 df.colums 我明白了,但我应该如何修改呢?

The logical structure df.colums I understand, but how should I be modifying it?

推荐答案

Drop 是一种非常灵活的方法,有很多种方法可以使用它:

Drop is a very flexible method, and there are quite a few ways to use it:

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

放一个使用元组的列:

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

或跨越某个级别,例如所有 a s:

or across a level, e.g. all as:

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

在0.14中,您还可以传递要丢弃的正则表达式...

还有一种方法可以放弃索引/列的整个级别:

There's also a way to drop the entire level of a index/column:

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

这篇关于从MultiIndex中删除单个(子)列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆