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

如何将多个不同长度的列表转换为Pandas DataFrame并避免索引报错

报错原因

你遇到list index out of range报错的核心原因是pandas构造DataFrame时默认要求所有列的元素数量完全一致,你现有列表长度分别为7、28、784、3136,刚好是逐次乘4的倍数关系,属于层级展开的多维度数据,需要先做维度对齐再构造DataFrame。

解决方案

方案1:简单重复对齐(适用于全量平铺展开的场景)

通过numpy的repeat方法按照最长列表长度(3136)对短列表进行等比例重复:

import pandas as pd
import numpy as np

# raw_data为你存储原始列表的字典,key为列名,value为对应列表
# 例如 raw_data = {"x": x列表, "y": y列表, "base_price": base_price列表, ...}
repeat_rule = {
    "x": 448, # 3136 /7 = 448
    "y": 448,
    "base_price": 112, # 3136 /28 = 112
    "entry_price": 4, # 3136 /784 =4
    "exit_price": 4,
    "high": 4,
    "strike": 4,
    "option_type": 4,
    "expiry": 4,
    "time": 4,
    "Gap": 4,
    "sl_exit_price": 1,
    "pnl": 1,
    "boolean": 1
}

aligned_data = {}
for col, raw_list in raw_data.items():
    aligned_data[col] = np.repeat(raw_list, repeats=repeat_rule[col]).tolist()

df = pd.DataFrame(aligned_data)

方案2:逐级合并(适用于分组嵌套的场景)

如果你的数据是分层嵌套关系(每个x/y对应4条base_price,每个base_price对应28条784长度的交易数据,每条交易数据对应4条平仓/损益数据),可以用临时键逐级合并避免错误重复:

import pandas as pd

# 构造各层级基础表
level_1 = pd.DataFrame({"x": x, "y": y})
level_1["tmp_key1"] = level_1.index.repeat(4)

level_2 = pd.DataFrame({"base_price": base_price})
level_2["tmp_key1"] = range(len(level_2))
level_2["tmp_key2"] = level_2.index.repeat(28)

level_3 = pd.DataFrame({
    "entry_price": entry_price, "exit_price": exit_price, "high": high,
    "strike": strike, "option_type": option_type, "expiry": expiry,
    "time": time, "Gap": Gap
})
level_3["tmp_key2"] = range(len(level_3))
level_3["tmp_key3"] = level_3.index.repeat(4)

level_4 = pd.DataFrame({
    "sl_exit_price": sl_exit_price, "pnl": pnl, "boolean": boolean
})
level_4["tmp_key3"] = range(len(level_4))

# 逐级合并并删除临时列
df = level_1.merge(level_2, on="tmp_key1")\
            .merge(level_3, on="tmp_key2")\
            .merge(level_4, on="tmp_key3")\
            .drop(columns=["tmp_key1", "tmp_key2", "tmp_key3"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:54:06