You need to enable JavaScript to run this app. 列数不固定场景下Pandas多索引数据表的透视实现方法
优惠活动
大模型
产品
解决方案
定价
更多

列数不固定场景下Pandas多索引数据表的透视实现方法

Pandas 动态商店宽表转换实现方案

核心需求匹配

针对逐行顾客交易明细转商店维度宽表的场景,实现完全动态适配列数的转换逻辑,无需提前预估单店顾客规模、预设固定列名。

可落地实现代码

前置:生成测试原始数据

import pandas as pd
df2 = pd.DataFrame({"shop":['a','a','a','b'],
                   "shop_name":['best_shop',"best_shop","best_shop","good_shop"],
                   "customer":['customer_1','customer_2','customer_3','customer_4'],
                   "month_of_purchase":['Jul','Jul','Aug','Aug']})

转换逻辑

  • 按商店维度分组,为组内每条消费记录生成动态序号,适配不同规模的顾客量
  • 将顾客标识、购买月份两类字段,结合动态序号生成无预设的列名,避免列名冲突
  • 拼接两类待转长表,通过透视自动生成宽表,列数完全跟随实际数据规模动态扩展
# 按商店分组生成记录动态序号
df2['record_seq'] = df2.groupby(['shop', 'shop_name']).cumcount()

# 生成顾客类别的列名与值映射
df2['customer_col'] = 'customer_' + (df2['record_seq'] + 1).astype(str)
# 生成购买月份类别的列名与值映射
df2['month_col'] = 'purchase_month_' + (df2['record_seq'] + 1).astype(str)

# 拼接两类映射为统一长表
customer_melt = df2[['shop', 'shop_name', 'customer_col', 'customer']].rename(
    columns={'customer_col': 'field_name', 'customer': 'field_value'}
)
month_melt = df2[['shop', 'shop_name', 'month_col', 'month_of_purchase']].rename(
    columns={'month_col': 'field_name', 'month_of_purchase': 'field_value'}
)
unified_long = pd.concat([customer_melt, month_melt], ignore_index=True)

# 动态透视生成最终宽表
result_df = unified_long.pivot_table(
    index=['shop', 'shop_name'],
    columns='field_name',
    values='field_value',
    aggfunc='first'
).reset_index()

结果说明

运行上述代码后,每家商店将对应独立1行,表内列会自动根据单店实际消费顾客数扩展:

  • 商店a因为有3位消费顾客,会自动生成customer_1/customer_2/customer_3、purchase_month_1/purchase_month_2/purchase_month_3共6个业务列
  • 商店b因为仅1位消费顾客,仅自动生成customer_1、purchase_month_1两个业务列

整个过程没有硬编码固定列名,完全适配任意规模的单店顾客量。

注意:如果存在单顾客在同店多月消费的场景,可在生成分组序号前,先按shop, shop_name, customer, month_of_purchase做去重,避免生成重复冗余列。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 13:36:04