Python 熊猫多重指数中的鬼指数
我有以下数据:Python 熊猫多重指数中的鬼指数,python,pandas,Python,Pandas,我有以下数据: 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
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
现在我对索引进行筛选并删除“一”:
奇怪的是,“一”仍然出现在索引中(取决于我用来访问索引值的方法): 或:
你知道为什么索引中仍然显示“一”吗?使用,因为默认情况下过滤后索引没有更改,我想原因是性能:
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')
谢谢你,耶斯雷尔。我假设这意味着pandas隐式保存了它为
df
看到的一组索引?你能详细解释一下吗?@Carsten-我先不是,然后这个函数就是为了解决这个问题而创建的。
t.index.levels[1]
Index(['one', 'two'], dtype='object', name='second')
t.index.get_level_values(1)
Index(['two', 'two'], dtype='object', name='second')
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')