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

Python Pandas使用wide_to_long时如何修复stubnames错误?

报错根因

触发ValueError: stubname can't be identical to a column name.有3个直接原因:

  • 构造DataFrame时手动插入了两个无意义的空字符串列名,干扰函数的列匹配逻辑
  • 调用wide_to_long时第一个参数传入了原始字典dt,而非构造完成的DataFrame对象
  • suffix参数的正则表达式写法不规范,加上未将固定属性字段trt纳入分组键,导致函数误判存在与stubnames列表值完全同名的列
修正后可运行代码
import pandas as pd

# 原始源数据
dt = {'id': {0: 'x1', 1: 'x2', 2: 'x3', 3: 'x4', 4: 'x5', 5: 'x6', 6: 'x7', 7: 'x8', 8: 'x9', 9: 'x10'}, 'trt': {0: 'cnt', 1: 'cnt', 2: 'tr', 3: 'tr', 4: 'tr', 5: 'cnt', 6: 'tr', 7: 'tr', 8: 'cnt', 9: 'cnt'}, 'work.T1': {0: 0.6516556669957936, 1: 0.567737752571702, 2: 0.1135089821182191, 3: 0.5959253052715212, 4: 0.3580499750096351, 5: 0.4288094183430075, 6: 0.0519033221062272, 7: 0.2641776674427092, 8: 0.3987907308619469, 9: 0.8361341434065253}, 'play.T1': {0: 0.8647212258074433, 1: 0.6153524168767035, 2: 0.7751098964363337, 3: 0.3555686913896352, 4: 0.4058499720413238, 5: 0.7066469138953835, 6: 0.8382876652758569, 7: 0.2395891312044114, 8: 0.7707715332508087, 9: 0.3558977444190532}, 'talk.T1': {0: 0.5355970377568156, 1: 0.0930881295353174, 2: 0.169803041499108, 3: 0.8998324507847428, 4: 0.4226376069709658, 5: 0.7477464678231627, 6: 0.8226525799836963, 7: 0.9546536463312804, 8: 0.6854445093777031, 9: 0.5005032296758145}, 'work.T2': {0: 0.2754838624969125, 1: 0.2289039448369294, 2: 0.0144339059479534, 3: 0.7289645625278354, 4: 0.2498804717324674, 5: 0.1611832766793668, 6: 0.0170426501426845, 7: 0.4861003451514989, 8: 0.1029001718852669, 9: 0.8015470046084374}, 'play.T2': {0: 0.3543280649464577, 1: 0.9364325392525644, 2: 0.2458663922734558, 3: 0.4731414613779634, 4: 0.191560871200636, 5: 0.5832219698932022, 6: 0.4594731898978352, 7: 0.467434047954157, 8: 0.3998325555585325, 9: 0.5052855962421745}, 'talk.T2': {0: 0.0318881559651345, 1: 0.1144675880204886, 2: 0.468935475917533, 3: 0.3969867376144975, 4: 0.8336191941052675, 5: 0.7611217433586717, 6: 0.5733564489055425, 7: 0.447508045937866, 8: 0.0838020080700516, 9: 0.2191385473124683}}

# 构造DataFrame时删除多余的空名列
mydt = pd.DataFrame(dt)

# 宽表转长表
names = ['play', 'talk', 'work']
activities = pd.wide_to_long(
    mydt,
    stubnames=names,
    i=['id', 'trt'], # 将固定属性trt纳入分组标识,避免转换后字段丢失
    j='time',
    sep='.',
    suffix=r'T\d+' # 用原生字符串正则匹配T开头加数字的后缀,避免转义错误
).sort_index().reset_index()

print(activities)
关键修正说明
  • 移除构造DataFrame时手动添加的两个无意义空名列
  • 传入wide_to_long的第一个参数必须是构造完成的DataFrame对象,不能直接传入原始字典
  • 将固定属性字段trt加入i参数的分组键列表,保证转换后每行数据的分组属性正确保留
  • suffix参数使用原生正则字符串r'T\d+',准确匹配.T1/.T2格式的列后缀,避免函数列匹配失败

运行后输出的结构和预期完全一致:
目标输出结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:06:20