我有以下数据:
arrays = [['bar', 'bar', 'baz', 'baz'],
['one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
s = pd.Series(np.random.randn(4), index=index)
first second
bar one 1.791849
two 0.334121
baz one -0.655277
two -1.296491
现在我过滤索引并删除“一个”:
t = s[s.index.get_level_values(1) != "one"]
first second
bar two 0.334121
baz two -1.296491
奇怪的是,索引中仍然显示“一个”(取决于我用来访问索引值的方法):
t.index.levels[1]
Index(['one', 'two'], dtype='object', name='second')
或者:
t.index.get_level_values(1)
Index(['two', 'two'], dtype='object', name='second')
您是否知道为什么索引中仍显示“一个”?
答案 0 :(得分:4)
使用MultiIndex.remove_unused_levels
,因为默认情况下过滤后的索引未更改,我猜原因是性能:
print (t.index.remove_unused_levels())
MultiIndex([('bar', 'two'),
('baz', 'two')],
names=['first', 'second'])
print (t.index.remove_unused_levels().levels[1])
Index(['two'], dtype='object', name='second')