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

如何解决Pandas宽表转长表操作中的TypeError错误?

Pandas宽表转长表:修复explode方法的错误及替代方案

问题场景

现有数据如下:

import pandas as pd
df = pd.DataFrame({'Id': ['AA', 'BB', 'CC'], 'Value': [4, 2, 3]})

目标是将每行的Value列转换为从1到对应值的序列,再通过explode实现宽表转长表,但原代码报错:

df['Value'] = df.apply(list(range(1, df['Value'])))
df.explode('Value')

错误信息:

TypeError: 'Series' object cannot be interpreted as an integer

错误原因

df['Value']是整个Series对象,而range()需要传入单个整数,直接在apply里调用range(1, df['Value'])会把Series当成参数传入,导致类型错误。另外apply默认按列处理,需要指定axis=1来按行执行逻辑。

修复后的代码

用lambda对每行单独处理,同时注意range是左闭右开区间,要给Value加1才能包含目标值:

import pandas as pd
df = pd.DataFrame({'Id': ['AA', 'BB', 'CC'], 'Value': [4, 2, 3]})

# 生成每行对应的序列列表
df['Value'] = df.apply(lambda x: list(range(1, x['Value'] + 1)), axis=1)
# 展开列表实现长表转换
result = df.explode('Value')
print(result)

输出结果:

Id Value
0  AA     1
0  AA     2
0  AA     3
0  AA     4
1  BB     1
1  BB     2
2  CC     1
2  CC     2
2  CC     3

更高效的替代方案

如果数据量较大,apply的性能可能不足,可以用repeat结合分组计数的方式实现,避免生成列表:

import pandas as pd
df = pd.DataFrame({'Id': ['AA', 'BB', 'CC'], 'Value': [4, 2, 3]})

# 按Value值重复每行
df_repeat = df.loc[df.index.repeat(df['Value'])]
# 分组生成从1开始的序号
df_repeat['Value'] = df_repeat.groupby('Id').cumcount() + 1
print(df_repeat)

这个方法直接利用Pandas的向量化操作,性能比apply更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:36:26