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

如何从包含单个字典的列表的pandas Series创建DataFrame

问题原因

IndexError: list index out of range报错说明df['traking']列中存在长度为0的空列表行,循环到这类行时取li[0]就会触发越界错误。你单独打印li[0]能正常输出,是因为测试时只命中了非空的行,没有覆盖到空列表行。

解决方案

方案1:遍历逻辑增加空值判断

可以在循环时增加列表非空校验,按需选择保留空行的占位值或者直接跳过空行:

traking = df['traking'].tolist()
temp_list = []
for li in traking:
    # 列表非空时取第一个元素,空列表可以填充None或者直接跳过不append
    if li and len(li) > 0:
        temp_list.append(li[0])
    else:
        temp_list.append(None)

方案2:用pandas内置方法实现更简洁

直接用apply处理列,还可以一步把字典展开为新的DataFrame:

# 提取字典序列,空列表位置填充None
dict_series = df['traking'].apply(lambda x: x[0] if isinstance(x, list) and len(x) > 0 else None)
# 把字典序列直接转为新的DataFrame,需要和原表拼接的话可以搭配pd.concat使用
new_df = pd.DataFrame(dict_series.tolist())

空行定位方法

如果需要确认哪些行是空列表,可以执行以下代码排查:

print(df[df['traking'].apply(lambda x: len(x) == 0)])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:45:01