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

如何用Pandas实现宽表转长表并对齐关联列?

宽格式转长格式DataFrame的正确实现

问题场景

原始宽格式DataFrame:

import pandas as pd

df = pd.DataFrame({
    'time' : [1,2,3],
    'X1-Price': [10,12,11],
    'X1-Quantity' : [2,3,4],
    'X2-Price': [3,4,2],
    'X2-Quantity' : [1,1,1]
})

输出如下:

time  X1-Price  X1-Quantity  X2-Price  X2-Quantity
0     1        10            2         3            1
1     2        12            3         4            1
2     3        11            4         2            1

需要转换为如下长格式,按X1/X2拆分类型,同时保留price和quantity在同一行:

time type  quantity  price
0     1   X1         2     10
1     2   X1         3     12
2     3   X1         4     11
3     1   X2         1      3
4     2   X2         1      4
5     3   X2         1      2

此前使用pd.wide_to_long()时参数错误,得到空DataFrame:

pd.wide_to_long(df, i='time', j='value', stubnames=['X'])

输出:

Empty DataFrame
Columns: [X1-Price, X2-Price, X2-Quantity, X1-Quantity, X]
Index: []

正确实现方法

方法1:正确使用pd.wide_to_long()

错误原因是参数stubnames和分隔符设置不对。原始列名遵循[类型]-[指标]的结构,因此需要把**指标(Price、Quantity)**作为stubnames,指定分隔符sep='-',并通过suffix匹配类型部分(X1、X2):

result = pd.wide_to_long(
    df,
    stubnames=['Price', 'Quantity'],
    i='time',
    j='type',
    sep='-',
    suffix=r'\w+'
).reset_index()

# 调整列顺序并统一为小写列名
result = result[['time', 'type', 'Quantity', 'Price']].rename(columns={
    'Quantity': 'quantity',
    'Price': 'price'
})

输出符合预期:

time type  quantity  price
0     1   X1         2     10
1     1   X2         1      3
2     2   X1         3     12
3     2   X2         1      4
4     3   X1         4     11
5     3   X2         1      2

方法2:melt+str.split拆分重塑

如果对wide_to_long的参数逻辑不熟悉,可采用更直观的分步拆分方式:

  1. 用melt将宽格式转为长格式,保留time作为标识列
  2. 拆分variable列,分离出type和metric
  3. 用pivot将指标转为列,得到目标格式
# 1. 转长格式
melted = df.melt(id_vars='time', var_name='type_metric', value_name='value')

# 2. 拆分类型与指标
melted[['type', 'metric']] = melted['type_metric'].str.split('-', expand=True)

# 3. 重塑为目标格式
result = melted.pivot(
    index=['time', 'type'],
    columns='metric',
    values='value'
).reset_index().rename(columns=str.lower)

输出与方法1完全一致。

内容的提问来源于stack exchange,提问作者ℕʘʘḆḽḘ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:09:53