You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:54:01