Python pandas 按客户持有的产品数量拆分DataFrame数据集
Pandas DataFrame 按客户持有产品品类数拆分实现代码
核心逻辑
先统计每个客户持有的唯一产品品类数,再根据品类数筛选对应客户的全量记录即可完成拆分。
实现代码
方法1:先统计客户维度的品类数再匹配(适合大数据集)
# 统计每个客户的唯一产品品类数量 customer_prod_count = df0.groupby('Customer')['Product'].nunique().reset_index(name='prod_count') # 提取仅持有单一品类的客户清单 single_prod_customers = customer_prod_count[customer_prod_count['prod_count'] == 1]['Customer'].to_list() # 拆分得到两个DataFrame df1 = df0[df0['Customer'].isin(single_prod_customers)].reset_index(drop=True) df2 = df0[~df0['Customer'].isin(single_prod_customers)].reset_index(drop=True)
方法2:用transform生成标识列(写法更简洁,适合中小数据集)
# 直接在原表新增每个客户对应的产品品类数字段 df0['prod_count'] = df0.groupby('Customer')['Product'].transform('nunique') # 按品类数拆分后删除辅助字段 df1 = df0[df0['prod_count'] == 1].drop(columns='prod_count').reset_index(drop=True) df2 = df0[df0['prod_count'] > 1].drop(columns='prod_count').reset_index(drop=True)
说明
- 两种方法都用了
nunique()做产品去重统计,同一客户多次购买同一品类不会被误判为多品类 - 最终生成的df1、df2会保留原df0的所有字段,可直接用于后续价格字段分析
reset_index(drop=True)用于重置拆分后表的索引,不需要可以去掉
内容的提问来源于stack exchange,提问作者Pas
相关产品推荐
相关产品推荐

