如何用Pandas检查分组后某列特定值每组最多出现一次并处理
Pandas分组处理重复'test'记录方案
示例数据构造
先还原示例中的DataFrame:
import pandas as pd data = { 'A': [1,1,1,1,2,2,2,3,3], 'B': ['test','t','te','test','t','te','test','test','tes'], 'C': [342,4556,222,56456,234525,123,23434,777,665] } df = pd.DataFrame(data)
1. 定位B列'test'出现超过1次的分组
通过筛选B='test'的行,按A分组计数,即可找出违规分组:
# 统计每个分组中'test'的出现次数 test_group_counts = df[df['B'] == 'test'].groupby('A').size() # 筛选出次数>1的分组 problem_groups = test_group_counts[test_group_counts > 1].index.tolist() print("存在重复'test'的分组:", problem_groups) # 输出:[1]
2. 删除多余'test'记录,保留C列最小的那条
采用拆分处理的思路,确保非'test'行不受影响,仅处理违规分组的'test'行:
# 保留所有非'test'的行 non_test_records = df[df['B'] != 'test'] # 处理'test'行:违规分组只留C最小的记录,其他分组保留全部'test'行 clean_test_records = df[df['B'] == 'test'].groupby('A').apply( lambda group: group[group['C'] == group['C'].min()] if group.name in problem_groups else group ).reset_index(drop=True) # 合并结果并按A排序(可选,还原原数据的分组顺序) final_df = pd.concat([non_test_records, clean_test_records]).sort_values('A').reset_index(drop=True) print("处理后的结果:") print(final_df)
处理后的输出结果:
A B C 0 1 t 4556 1 1 te 222 2 1 test 342 3 2 t 234525 4 2 te 123 5 2 test 23434 6 3 test 777 7 3 tes 665
内容的提问来源于stack exchange,提问作者ArieAI
相关产品推荐
相关产品推荐

