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、revenuei:作为唯一标识的固定列,这里为客户唯一IDcustomer_codej:新生成的分类列的列名,用来存储主/次门店维度sep:原始列名中门店前缀和数值字段之间的分隔符,这里为下划线_suffix:匹配门店前缀的正则规则,.+可同时匹配main和secondary两种前缀
内容的提问来源于stack exchange,提问作者Yeahprettymuch
相关产品推荐
相关产品推荐

