如何使用Pandas实现同时关联A和B标签的列值筛选与计数
Hey, let's figure out how to solve this exact problem you're having with Pandas. I've got a couple of straightforward approaches that will get you the word list and count you're looking for.
Step-by-Step Implementation
First, let's start with the test DataFrame to replicate your input:
import pandas as pd # Recreate your input DataFrame data = { 'Column': ['A', 'B', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'A', 'B'], 'Another_column': ['word1', 'word1', 'word2', 'word3', 'word4', 'word5', 'word5', 'word6', 'word6', 'word7', 'word7'] } df = pd.DataFrame(data)
Approach 1: Using Unique Values and Set Subset Check
This method groups by Another_column, collects unique tags for each word, then filters groups that contain both "A" and "B":
# Group by Another_column and get unique Column values for each group grouped_tags = df.groupby('Another_column')['Column'].unique() # Filter groups where both "A" and "B" are present valid_words = grouped_tags[grouped_tags.apply(lambda x: {'A', 'B'}.issubset(set(x)))] # Extract results valid_word_list = valid_words.index.tolist() valid_count = len(valid_word_list) # Print output print("符合条件的word列表:", valid_word_list) print("统计数量:", valid_count)
Approach 2: Explicitly Check for "A" and "B" Presence
If you prefer more readability, you can explicitly flag whether each group has "A" and "B", then filter:
# Group by Another_column and create flags for A/B presence grouped_flags = df.groupby('Another_column')['Column'].agg( has_A=lambda x: 'A' in x.values, has_B=lambda x: 'B' in x.values ) # Filter groups where both flags are True valid_words = grouped_flags[(grouped_flags['has_A'] & grouped_flags['has_B'])].index.tolist() valid_count = len(valid_words) # Print output print("符合条件的word列表:", valid_words) print("统计数量:", valid_count)
Output
Both approaches will give you exactly what you need:
符合条件的word列表: ['word1', 'word5', 'word7'] 统计数量: 3
Key Notes
- Both methods exclude words that only have "A", only have "B", or have combinations like "B"+"C" (without "A")—which matches your exact requirements.
- The first approach uses set operations which are efficient for checking multiple value presence, while the second is more verbose but easier to follow if you're new to Pandas grouping.
内容的提问来源于stack exchange,提问作者lavo_hos
相关产品推荐
相关产品推荐

