考虑以下DataFrame:
arrays = [['foo', 'bar', 'bar', 'bar'],
['A', 'B', 'C', 'D']]
tuples = list(zip(*arrays))
columnValues = pd.MultiIndex.from_tuples(tuples)
df = pd.DataFrame(np.random.rand(4,4), columns = columnValues)
print(df)
foo bar
A B C D
0 0.859664 0.671857 0.685368 0.939156
1 0.155301 0.495899 0.733943 0.585682
2 0.124663 0.467614 0.622972 0.567858
3 0.789442 0.048050 0.630039 0.722298
我想要删除第一列,如下所示:
df.drop(df.columns[[0]], axis = 1, inplace = True)
print(df)
bar
B C D
0 0.671857 0.685368 0.939156
1 0.495899 0.733943 0.585682
2 0.467614 0.622972 0.567858
3 0.048050 0.630039 0.722298
这会产生预期结果,但保留列标签foo
和A
:
print(df.columns.levels)
[['bar', 'foo'], ['A', 'B', 'C', 'D']]
有没有办法从MultiIndex DataFrame中完全删除列,包括其标签?
编辑:正如约翰所建议的那样,我看了https://github.com/pydata/pandas/issues/12822。我得到的是它不是一个bug,但我相信建议的解决方案(https://github.com/pydata/pandas/issues/2770#issuecomment-76500001)对我不起作用。我在这里错过了什么吗?df2 = df.drop(df.columns[[0]], axis = 1)
print(df2)
bar
B C D
0 0.969674 0.068575 0.688838
1 0.650791 0.122194 0.289639
2 0.373423 0.470032 0.749777
3 0.707488 0.734461 0.252820
print(df2.columns[[0]])
MultiIndex(levels=[['bar', 'foo'], ['A', 'B', 'C', 'D']],
labels=[[0], [1]])
df2.set_index(pd.MultiIndex.from_tuples(df2.columns.values))
ValueError: Length mismatch: Expected axis has 4 elements, new values have 3 elements
答案 0 :(得分:3)
As of pandas 0.20, pd.MultiIndex
has a method pd.MultiIndex.remove_unused_levels
df.columns = df.columns.remove_unused_levels()
Our savior is pd.MultiIndex.to_series()
it returns a series of tuples restricted to what is in the DataFrame
df.columns = pd.MultiIndex.from_tuples(df.columns.to_series())