
本文介绍如何基于每组商品(如鞋子、衬衫)中已知的尺寸顺序与物理维度(长宽高体积),对缺失值进行线性插值填充;核心是将混合型尺寸(如 ‘s’/’xl’/’3’)统一映射为有序分类类型,再按排序位置执行等距线性填充。
在电商或仓储系统中,SKU 尺寸常以非数值形式表示(如 ‘s’, ‘2xl’, ‘3’),但其对应的实际物理属性(长度、宽度、高度、体积)具有单调递增趋势。直接对 NaN 值用均值或前向填充会丢失这种结构性关系。理想方案是:按尺寸语义顺序排列数据,再在线性空间中等距生成中间值。
pandas 提供了 CategoricalDtype(ordered=True) 作为解决该问题的关键工具。它允许我们显式定义尺寸的逻辑顺序,并使 .sort_values() 和 .interpolate() 能正确理解 ‘s’
以下为完整可复用实现:
import pandas as pd import numpy as np # 示例数据(含多类 skugroup) data_wm = { 'sku': [6124, 7343, 7981, 5761, 1570, 7223, 4107, 8187, 4653, 1802, 4079], 'skugroup': ['shoes', 'shoes', 'shoes', 'shoes', 'shoes', 'shoes', 'shirt', 'shirt', 'shirt', 'shirt', 'shirt'], 'size': ['s', 'm', 'l', 'xl', '2xl', '3xl', '1', '2', '3', '4', '5'], 'length': [1.5, np.nan, np.nan, np.nan, np.nan, 6, 1, np.nan, np.nan, np.nan, 4], 'width': [2, np.nan, np.nan, np.nan, np.nan, 8, 2, np.nan, np.nan, np.nan, 5], 'height': [2, np.nan, np.nan, np.nan, np.nan, 3, 3, np.nan, np.nan, np.nan, 6], 'volume': [6, np.nan, np.nan, np.nan, np.nan, 144, 6, np.nan, np.nan, np.nan, 120] } df = pd.DataFrame(data_wm) # ✅ 定义全局尺寸顺序(支持扩展:新增 skugroup 只需追加对应尺寸) txt_size = ['xs', 's', 'm', 'l', 'xl', '2xl', '3xl', '4xl'] num_size = [str(i) for i in range(1, 21)] # 支持 1~20 号 all_sizes = txt_size + num_size # 创建有序分类类型(关键!) sizes_dtype = pd.CategoricalDtype(all_sizes, ordered=True) # ✅ 核心逻辑:按尺寸顺序排序 → 分组 → 线性插值 cols_to_fill = ['length', 'width', 'height', 'volume'] # 注意:必须先转换 dtype 再排序,否则 sort_values 无法识别语义顺序 df_filled = (df.astype({'size': sizes_dtype}) .sort_values(['skugroup', 'size']) # 先分组内排序 .groupby('skugroup', sort=False)[cols_to_fill] .apply(lambda g: g.interpolate(method='linear')) .reset_index(drop=True)) # 合并回原始索引(保持原顺序) df[cols_to_fill] = df_filled[cols_to_fill]
✅ 输出效果(自动对齐尺寸顺序并线性填充):
sku skugroup size length width height volume 0 6124 shoes s 1.50 2.00 2.00 6.0 1 7343 shoes m 2.40 3.20 2.20 33.6 2 7981 shoes l 3.30 4.40 2.40 61.2 3 5761 shoes xl 4.20 5.60 2.60 88.8 4 1570 shoes 2xl 5.10 6.80 2.80 116.4 5 7223 shoes 3xl 6.00 8.00 3.00 144.0 6 4107 shirt 1 1.00 2.00 3.00 6.0 7 8187 shirt 2 1.75 2.75 3.75 34.5 8 4653 shirt 3 2.50 3.50 4.50 63.0 9 1802 shirt 4 3.25 4.25 5.25 91.5 10 4079 shirt 5 4.00 5.00 6.00 120.0
⚠️ 注意事项:
- 顺序必须完整且无歧义:’2′ 和 ‘2xl’ 在列表中不能冲突(当前设计已隔离文本与数字前缀);
- 插值依赖端点值:若某组仅有一个非空值,interpolate() 不会填充(需配合 limit_direction=’both’ 或预处理);
- 扩展性强:新增 skugroup(如 ‘pants’)只需确保其 size 值已包含在 all_sizes 中,无需修改逻辑;
- 性能提示:大数据集建议用 groupby(…).transform(…) 替代 apply,避免索引重置开销。
该方法兼顾语义合理性与工程可维护性,是处理混型尺寸+连续物理量缺失值的推荐范式。