基于多列条件的Python Dataframe去重分类与统计实现方法
Pandas DataFrame 多条件分类统计实现方案
直接使用Pandas库即可完成全流程需求,以下是可直接运行的实现代码(默认原始数据已加载为DataFrame对象df,包含Customer_ID、Category、Type、Delivery、Download/Upload字段):
import pandas as pd # 1. 去除重复行 # 按Customer_ID、Category、Type、Delivery、Download/Upload组合去重,仅保留第一条 # 若重复判定仅需匹配Customer_ID+Category,可修改subset参数为['Customer_ID', 'Category'] df_dedup = df.drop_duplicates( subset=['Customer_ID', 'Category', 'Type', 'Delivery', 'Download/Upload'], keep='first' ) # 2. 统计单用户单品类下的主导交易类型(Buy/Sell出现次数更高的为主) user_category_type = df_dedup.groupby(['Customer_ID', 'Category'])['Type'].agg( # 取出现次数最多的Type,次数相等时默认取第一个出现的值 dominant_type=lambda x: x.value_counts().index[0] ).reset_index() # 3. 识别单用户单品类下的交付方式使用情况 user_category_delivery = df_dedup.groupby(['Customer_ID', 'Category']).agg( # 只要使用过一次就标记为True,若字段为'是/否'字符串,可替换为lambda x: '是' in x.values Delivery=('Delivery', 'any'), Download_Upload=('Download/Upload', 'any') ).reset_index() # 4. 合并交易类型和交付方式结果 base_result = user_category_type.merge( user_category_delivery, on=['Customer_ID', 'Category'], how='inner' ) # 5. 统计同品类同交易类型的用户计数 category_type_cnt = base_result.groupby(['Category', 'dominant_type'])['Customer_ID'].nunique().reset_index( name='同品类同类型计数' ) # 6. 合并得到最终结果,调整字段符合输出要求 final_result = base_result.merge( category_type_cnt, on=['Category', 'dominant_type'], how='left' ).rename( columns={'dominant_type': 'Type', 'Download_Upload': 'Download/Upload'} )[['Customer_ID', 'Category', 'Type', 'Delivery', 'Download/Upload', '同品类同类型计数']]
自定义调整说明
- 若需处理Buy和Sell出现次数相等的场景,可修改
dominant_type的计算逻辑,增加次数相等时的分支判断,例如返回'两者均衡' - 若交付方式字段为字符串类型(如
'是'/'否'),将agg中的any方法替换为lambda x: '是' in x.values即可 - 若需要新增交付方式合并字段(仅Delivery/仅Download/Upload/两者都用),可新增apply逻辑生成对应列
内容的提问来源于stack exchange,提问作者V.Nouri
相关产品推荐
相关产品推荐

