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

如何用for循环读取多个不同变量名的Pandas DataFrame

解决方法:遍历多个Pandas DataFrame并提取指定列

你的问题出在对列表的访问方式上——你把DataFrame对象直接放进了列表,却试图用字典的键访问方式来获取text列,这自然会报错。下面是具体的修正步骤和实现代码:

1. 先确认DataFrame初始化(和你的代码一致)

import pandas as pd

df1 = pd.DataFrame({'index':1,'text':['this is text in df1','this is text in df1']})
df2 = pd.DataFrame({'index':1,'text':['this is text in df2','this is text in df2']})
df3 = pd.DataFrame({'index':1,'text':['this is text in df3','this is text in df3']})

2. 正确的遍历方式

首先把所有DataFrame存入列表,然后逐个遍历列表中的DataFrame对象,提取text列并转为Python列表:

方式一:直接打印每个text列的列表

# 存储所有DataFrame的列表
df_collection = [df1, df2, df3]

# 遍历每个DataFrame
for df in df_collection:
    # 提取text列并转为普通列表
    text_list = df['text'].tolist()
    print(text_list)

运行后会输出:

['this is text in df1', 'this is text in df1']
['this is text in df2', 'this is text in df2']
['this is text in df3', 'this is text in df3']

方式二:收集所有text列的列表到一个大列表中

如果想把所有结果保存起来后续使用,可以这样做:

all_text_lists = []
for df in df_collection:
    all_text_lists.append(df['text'].tolist())

# 查看收集到的结果
print(all_text_lists)

输出结果:

[['this is text in df1', 'this is text in df1'], ['this is text in df2', 'this is text in df2'], ['this is text in df3', 'this is text in df3']]

为什么你的原代码会报错?

你写的df_names=[df1,df2,df3]是创建了一个存储DataFrame对象的列表,而不是字典。列表只能通过整数索引(比如df_names[0])访问元素,不能用字符串键(df_names['text']),这会触发TypeError: list indices must be integers or slices, not str错误。正确的逻辑是先遍历列表中的每个DataFrame,再对单个DataFrame提取text列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:44:42