当我用0级索引值将MultiIndex
DataFrame
切片时,我想知道可能落在该初始值下的1+级索引值。如果我的措辞不合理,举个例子:
>>> arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
... ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],
... ['a','b','a','b','b','b','b','b']]
>>> tuples = list(zip(*arrays))
>>> index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second','third'])
>>> s = pd.Series(np.random.randn(8), index=index)
>>> s
first second third
bar one a -0.598684
two b 0.351421
baz one a -0.618285
two b -1.175418
foo one b -0.093806
two b 1.092197
qux one b -1.515515
two b 0.741408
dtype: float64
s
的index
看起来像:
>>> s.index
MultiIndex(levels=[[u'bar', u'baz', u'foo', u'qux'], [u'one', u'two'], [u'a', u'b']],
labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 1, 1]],
names=[u'first', u'second', u'third'])
当我只取s
的部分,它的first
索引值是foo
,然后查找我得到的索引:
>>> s_foo = s.loc['foo']
>>> s_foo
second third
one b -0.093806
two b 1.092197
dtype: float64
>>> s_foo.index
MultiIndex(levels=[[u'one', u'two'], [u'a', u'b']],
labels=[[0, 1], [1, 1]],
names=[u'second', u'third'])
我想让s_foo
的index
表现为s
的更高级别不存在,然而我们可以在s_foo.index
的levels
属性中看到,a
仍然被认为是索引third
的潜在值,尽管s_foo
只有b
作为可能值
本质上,我想找到的是third
的所有可能的foo_s
值,即b
并且只有b
。现在我想set(s_foo.reset_index()['third'])
,但我希望有一个更优雅的解决方案
您可以创建sèfoo并显式删除未使用的级别:
重置索引似乎是正确的方法,似乎你不希望它成为一个索引(结果就是索引的工作方式)
或者如果你想的话
相关问题 更多 >
编程相关推荐