从多索引数据框中删除二级列

考虑这个数据框:

import pandas as pd
import numpy as np
iterables = [['bar', 'baz', 'foo'], ['one', 'two']]
index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 6), index=['A', 'B', 'C'], columns=index)
print(df)
first        bar                 baz                 foo          
second       one       two       one       two       one       two
A      -1.954583 -1.347156 -1.117026 -1.253150  0.057197 -1.520180
B       0.253937  1.267758 -0.805287  0.337042  0.650892 -0.379811
C       0.354798 -0.835234  1.172324 -0.663353  1.145299  0.651343

我想从每列中删除“一个”,同时保留其他结构。
最终结果看起来像这样:

first        bar       baz       foo          
second       two       two       two
A      -1.347156 -1.253150 -1.520180
B       1.267758  0.337042 -0.379811
C      -0.835234 -0.663353  0.651343

回答

使用drop

df.drop('one', axis=1, level=1)
first        bar       baz       foo
second       two       two       two
A       0.127419 -0.319655 -0.878161
B      -0.563335  1.193819 -0.469539
C      -1.324932 -0.550495  1.378335


以上是从多索引数据框中删除二级列的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>