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

pandas pivot_table返回行数异常 部分CustomerId丢失如何解决

pandas pivot_table丢失CustomerId行问题排查

核心原因(按出现概率排序)

  • 高概率:ProductName列存在空值,被过滤的223个CustomerId的所有销售记录的ProductName均为NaN。pivot_table默认会忽略columns参数对应列为NaN的行,若某个客户的所有记录的ProductName都为空,这些记录会被完全排除,最终该客户不会出现在透视结果中。
  • 次概率:Quantity列存在非数值类型/全空值,部分客户的所有Quantity值无法参与sum运算,聚合后无有效结果被过滤。
  • 低概率:使用的pandas版本低于1.0,部分客户的Quantity全为NaN,旧版本pandas对全NaN序列sum返回NaN,无有效聚合结果被过滤。

排查步骤

  1. 验证是否为ProductName空值导致:
# 统计每个客户的非空ProductName数量
customer_valid_prod = sales_per_customer.groupby('CustomerId')['ProductName'].agg(lambda x: x.notna().sum())
# 提取无有效ProductName的客户ID
missing_cids = customer_valid_prod[customer_valid_prod == 0].index.tolist()
print(len(missing_cids)) # 输出为223即可确认问题
  1. 若上述排查不成立,验证Quantity列问题:
# 查看Quantity列数据类型
print(sales_per_customer['Quantity'].dtype)
# 统计每个客户的非空Quantity数量
customer_valid_qty = sales_per_customer.groupby('CustomerId')['Quantity'].agg(lambda x: x.notna().sum())
missing_cids_qty = customer_valid_qty[customer_valid_qty == 0].index.tolist()
print(len(missing_cids_qty))

解决方案

针对ProductName空值问题

先填充ProductName空值为占位符,再执行透视,可额外添加fill_value=0将无销量产品的结果填充为0,更贴合业务需求:

sales_per_customer['ProductName'] = sales_per_customer['ProductName'].fillna('未知产品')
products_sum = pd.pivot_table(sales_per_customer, 
        values='Quantity', 
        index='CustomerId', 
        columns='ProductName',
        aggfunc = "sum",
        fill_value=0
).reset_index()

通用兜底方案

如果需要强制保留所有CustomerId,可在透视完成后手动对齐所有客户ID:

# 获取原数据全量客户ID
all_cids = sales_per_customer['CustomerId'].unique()
# 对齐索引补全缺失客户
products_sum = products_sum.set_index('CustomerId').reindex(all_cids).fillna(0).reset_index()

内容的提问来源于stack exchange,提问作者PhilM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:30:01