列上带有 .loc 的多索引

问题描述 投票:0回答:1

我有一个具有多索引的数据框,如下

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"])

s = pd.DataFrame(np.random.randn(8), index=index).T

看起来像这样

                    bar                      baz                   foo                      qux
          one       two          one         two         one       two          one         two
0   -0.144135   0.625481    -2.139184   -1.066893   -0.123791   -1.058165   0.495627    -0.654353

文档说要按以下方式索引

df.loc[:, (slice("bar", "two"), ...)]

我也这么做

s.loc[:, (slice("bar", "two"):(slice("baz", "two"))]

这给了我一个

SyntaxError

  Cell In[98], line 3
    s.loc[:, (slice("bar", "two"):(slice("baz", "two")))]
                                 ^
SyntaxError: invalid syntax

在我的具体用例中[尽管超出了这个问题的范围],1 级索引的类型为时间戳[年],但我认为答案应该是相同的。通过多索引列访问一系列多索引项的正确方法是什么?

python pandas multi-index
1个回答
0
投票

如果你想获取从第二条到第二条的数据,可以使用以下代码。

s.loc[:, ("bar", "two"):("baz", "two")]
© www.soinside.com 2019 - 2024. All rights reserved.