回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>当我用0级索引值将<code>MultiIndex</code><code>DataFrame</code>切片时,我想知道可能落在该初始值下的1+级索引值。如果我的措辞不合理,举个例子:</p>
<pre><code>>>> 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
</code></pre>
<p><code>s</code>的<code>index</code>看起来像:</p>
<pre><code>>>> 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'])
</code></pre>
<p>当我只取<code>s</code>的部分,它的<code>first</code>索引值是<code>foo</code>,然后查找我得到的索引:</p>
<pre><code>>>> 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'])
</code></pre>
<p>我想让<code>s_foo</code>的<code>index</code>表现为<code>s</code>的更高级别不存在,然而我们可以在<code>s_foo.index</code>的<code>levels</code>属性中看到,<code>a</code>仍然被认为是索引<code>third</code>的潜在值,尽管<code>s_foo</code>只有<code>b</code>作为可能值</p>
<p>本质上,我想找到的是<code>third</code>的所有可能的<code>foo_s</code>值,即<code>b</code>并且只有<code>b</code>。现在我想<code>set(s_foo.reset_index()['third'])</code>,但我希望有一个更优雅的解决方案</p>