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

Python中宽格式DataFrame转长格式:wide_to_long函数异常

解决pandas wide_to_long转换宽格式DataFrame的问题

我来帮你搞定这个wide_to_long的转换问题!先看一下你的DataFrame结构:

import pandas as pd

df = pd.DataFrame({
    'Mode': ['car', 'car', 'car', 'air', 'air', 'car', 'car', 'air', 'air'],
    'id':[1,2,3,4,5,6,7,8,9],
    'time.air': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
    'time.car': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]
})

你想用wide_to_long转成窄格式但没得到预期结果,大概率是参数设置没匹配上你的列名规则。wide_to_long的核心是识别列名的前缀(stubname)、分隔符(sep)和后缀(suffix),咱们一步步来:

正确的转换代码

result = pd.wide_to_long(
    df,
    stubnames='time',  # 列名的共同前缀:time.air和time.car的前缀是time
    i=['id', 'Mode'],  # 唯一标识原始行的列,id本身唯一,也可以只传['id']
    j='transport',     # 后缀部分要转换成的新列名,对应air/car类别
    sep='.',           # 前缀和后缀的分隔符,你的列名用.分隔
    suffix='\\w+'      # 匹配后缀的正则,\w+对应字母组合air/car
).reset_index()

转换后的预期结果

运行后会得到标准的窄格式DataFrame:

idModetransporttime
1carair2.8
1carcar3.4
2carair2.9
2carcar3.8
3carair2.2
3carcar2.9
............

常见坑点提醒

  • 没指定sep='.'的话,wide_to_long默认用空字符串分隔,无法识别前缀和后缀;
  • suffix默认是'\d+'(匹配数字),但你的后缀是字母,必须改成'\\w+'或者'(air|car)'精准匹配;
  • i参数必须是能唯一标识原始行的列,否则会出现重复索引问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:33:44