You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从多级索引Pandas DataFrame中按指定索引列表提取指定列?

解决多级索引Pandas DataFrame按第0级索引筛选并提取指定列的问题

Hey, let's work through your problem of filtering a multi-index Pandas DataFrame by level 0 indices and extracting the 'index' column.

Your initial approach with isin is on the right track, but there are cleaner and more efficient ways to get the result you want. Here are a couple of solid solutions:

1. Directly filter with .loc (simplest method)

Since you're targeting level 0 of the multi-index, you can use .loc directly to specify the filter list and then pull the 'index' column in one go:

filtered_list = [3, 5, 7]
# Get the 'index' column for rows where level 0 index is in the filtered list
result = df.loc[filtered_list, 'index']
print(result)

This is more straightforward than using isin because .loc inherently recognizes the top-level index when you pass a list of values to it.

2. Refine your original isin approach

If you prefer sticking with the isin method, you can separate the mask creation for clarity (though the end result is the same):

filtered_list = [3, 5, 7]
# Create a boolean mask for level 0 indices in the filtered list
mask = df.index.isin(filtered_list, level=0)
# Filter the DataFrame and extract the 'index' column
result = df.loc[mask, 'index']
print(result)

Example Output Verification

Using your sample data (formatted properly with multi-index), here's what you can expect from either method:
For rows where level 0 index is 3, 5, or 7, the output result will be:

3  0  4.0    3.0
5  0  6.0    5.0
7  0  1.0    7.0
   1  3.0    7.0
Name: index, dtype: float64

Troubleshooting Tip

If your original code wasn't behaving as expected, double-check two things:

  • Make sure you're targeting the correct index level (level=0 is indeed the top-level index you want to filter)
  • Confirm that the column name 'index' doesn't conflict with your DataFrame's index name (this can cause unexpected behavior—use df.columns to verify column names)

内容的提问来源于stack exchange,提问作者Fadri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:22:32