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

Pandas如何透视多列数据合并为少数字段并保留主/次业务维度信息

解决方案

你可以直接使用Pandas内置的pd.wide_to_long()方法实现需求,仅需1行核心代码即可完成转换,完整可运行代码如下:

import pandas as pd

# 原始数据生成
df = pd.DataFrame({"customer_code": ['1234','3411','9303'],
                   "main_purchases": [3,10,5],
                   "main_revenue": [103.5,401.5,99.0],
                   "secondary_purchases": [1,2,4],
                   "secondary_revenue": [43.1,77.5,104.6]
                  })

# 核心转换代码
res = pd.wide_to_long(df, stubnames=['purchases', 'revenue'], i='customer_code', j='store_type', sep='_', suffix='.+').reset_index()

# 可选:将门店类型替换为中文
res['store_type'] = res['store_type'].replace({'main': '主门店', 'secondary': '次门店'})

参数说明

  • stubnames:需要保留的数值字段公共名称,这里对应你要独立出来的purchases、revenue
  • i:作为唯一标识的固定列,这里为客户唯一IDcustomer_code
  • j:新生成的分类列的列名,用来存储主/次门店维度
  • sep:原始列名中门店前缀和数值字段之间的分隔符,这里为下划线_
  • suffix:匹配门店前缀的正则规则,.+可同时匹配main和secondary两种前缀

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:24:02