pandas - 如何通过仅指定第 n 个索引级别来从 pandas DataFrame 中获取 select 行?

我有一个带有多级行索引的 pandas DataFrame:

operators  license
                       sum      sum
City      Year
-----------------------------------       
New York  2020          44       A2
Chicago   2020          30       A2
Boston    2020          33       A1
New York  2021          48       A2
Chicago   2021          30       A2 
Boston    2021          41       A1

我可以通过仅指定行索引的级别 0 来使用 .loc 的 select 行:

df.loc[("Boston", )]

但是如何在不指定级别 0 的情况下 select 级别 1 为 2020 的所有行?经过一番搜索,我发现 query 给了我正在寻找的确切结果:

df.query("Year == 2020")

现在我想知道如何使用 .loc 来实现这一点?

回答1

根据https://pandas.pydata.org/docs/user_guide/advanced.html#cross-section,你可以使用

out = df.loc[(slice(None), 2020), :]

idx = pd.IndexSlice
out = df.loc[idx[:, 2020], :]

out = df.xs(2020, level='Year', drop_level=False)
out = df.xs(2020, level=1, drop_level=False)
print(out)

              operators license
                    sum     sum
City     Year
New York 2020        44      A2
Chicago  2020        30      A2
Boston   2020        33      A1

相似文章

随机推荐

最新文章