Pandas多索引查询:输出包含在二级索引中的所有一级索引项
Hey there! Let's break down how to solve this problem step by step. First, let's confirm the structure of your grouped DataFrame grpd_df: when you run that groupby + apply combo with a reset index inside, you end up with a MultiIndex—the first level (level 0) is your grouping key (item values like hat, scarf, belt), and the second level (level 1) is the reset row index for each individual group.
First, let's make sure we're working with the same setup (I'll add the missing pandas import):
import pandas as pd data = {'colour': ['red','purple','green','purple','blue','red'], 'item': ['hat','scarf','belt','belt','hat','scarf'], 'material': ['felt','wool','leather','wool','plastic','wool']} df = pd.DataFrame(data=data) grpd_df = df.groupby(df['item']).apply(lambda df: df.reset_index(drop=True))
Method 1: Get All Unique First-Level Index Entries
If your goal is to pull every first-level index entry that has corresponding second-level index entries (i.e., every grouping key that has data), you can directly extract the unique values from the first index level:
# Extract unique values from the first index level (level 0 = 'item') unique_first_level = grpd_df.index.get_level_values(0).unique() print(unique_first_level)
Output:
Index(['hat', 'scarf', 'belt'], dtype='object', name='item')
To convert this to a regular Python list:
first_level_list = unique_first_level.tolist() print(first_level_list) # Output: ['hat', 'scarf', 'belt']
Method 2: Filter First-Level Entries for a Specific Second-Level Value
If you need to find first-level index entries that map to a specific second-level index value (e.g., all items where the group has a row with index 1), use this approach:
# Filter rows where second-level index is 1, then get unique first-level entries target_secondary_value = 1 matching_first_level = grpd_df[grpd_df.index.get_level_values(1) == target_secondary_value].index.get_level_values(0).unique() print(matching_first_level)
Output:
Index(['hat', 'scarf', 'belt'], dtype='object', name='item')
Method 3: Check if a Specific First-Level Entry Exists
If you just want to verify if a particular first-level entry has any second-level index entries (i.e., if the group exists), use isin:
# Check if 'hat' is present in the first index level has_hat = 'hat' in grpd_df.index.get_level_values(0) print(has_hat) # Output: True
Quick Note
The core tool here is MultiIndex.get_level_values()—you can either use the level number (0 for first, 1 for second) or the level name (if your index has names, like item for level 0 in this case) to target the right index level.
内容的提问来源于stack exchange,提问作者CGully

