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

Python循环存入id与dataframe并按id检索对应数据的实现问题

核心错误原因

  • 空列表初始化时没有对应位置的字典元素,直接使用dfList[index][key]赋值会触发索引越界、键不存在报错
  • list.append()方法不支持直接传入赋值表达式作为参数,原代码语法不合法

真实CSV读取场景实现

import os
import pandas as pd

csvfiles = ['file1.csv', 'file2.csv']
dfList = []
for csvfile in csvfiles:
    file_path = os.path.join('C:/Documents', csvfile)
    df = pd.read_csv(file_path)
    # 构造符合要求的字典后追加到列表
    dfList.append({
        'id': csvfile,
        'dataframe': df
    })

测试用例场景实现

首先修正原测试代码中d2定义多写一个右方括号的语法错误,完整实现如下:

import pandas as pd

d = {'id': [1, 2, 3, 4], 'horstid': [11, 22, 33, 33]}
df = pd.DataFrame(data=d)
d2 = {'id': [1, 2, 3, 4]}
df2 = pd.DataFrame(data=d2)
csvfiles = [df, df2]

dfList = []
for index, csvfile in enumerate(csvfiles):
    dfList.append({
        'id': f"File{index+1}", # 索引从0开始,加1得到File1、File2的命名
        'dataframe': csvfile
    })

按id提取DataFrame的方法

方法1:遍历匹配(适合少量查询场景)

target_id = 'File1'
df_new = next(item['dataframe'] for item in dfList if item['id'] == target_id)
print(df_new)

输出结果:

id  horstid
0   1       11
1   2       22
2   3       33
3   4       33

方法2:转为字典查询(适合高频查询场景,效率更高)

# 把列表转为id为键、dataframe为值的字典
df_dict = {item['id']: item['dataframe'] for item in dfList}
# 直接通过id取值
df_new = df_dict['File1']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:45:03