如何使用基于 integer-location 的索引访问 MultiIndex 数据框中的行

How to access rows in a MultiIndex dataframe by using integer-location based indexing

假设我有以下 MultiIndex DataFrame,标题为 df:

arrays = [["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
          ["one", "two", "one", "two", "one", "two", "one", "two"],]
tuples = list(zip(*arrays))

index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])

df = pd.Series(np.random.randn(8), index=index)

如果我想访问与 baz 关联的所有行,例如,我会使用 cross-section:df.xs(('baz')).

但是有没有办法通过引用第一级中的整数位置来访问行,类似于 iloc 用于单索引数据帧?在我的示例中,我认为那将是索引位置 1.

我尝试使用 .loc 的解决方法,如下所示:

(df.loc[[df.index.get_level_values(0)[1]]]

但是returns第一组行与bar关联。我相信这是因为 integer-location 1 仍在 bar 之内。我必须参考 2 才能到达 baz.

我可以让位置 0、1、2 和 3 分别引用 bar、baz、foo 和 qux 吗?

您可以使用levels

df.xs(df.index.levels[0][1])
second
one   -1.052578
two    0.565691
dtype: float64

更多详情

df.index.levels[0][0]
'bar'
df.index.levels[0][1]
'baz'