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

为列表中各DataFrame添加文件名列时遇AttributeError问题求助

解决Spyder中给DataFrame添加文件名列的AttributeError问题

嘿,我一眼就看到你代码里的问题啦——你在尝试用tempList[i].all_filenames[i]获取文件名,但all_filenames是你在外部定义的独立列表,并不是DataFrame对象的属性,所以Python会报错说DataFrame没有all_filenames这个属性,这就是问题根源。

错误原因拆解

你写的这行代码:

tempList[i]['Timestamp'] = tempList[i].all_filenames[i]

这里的tempList[i]是一个DataFrame,你试图访问它的all_filenames属性,但这个属性根本不存在。all_filenames是你在代码开头定义的文件名列表,直接用all_filenames[i]就能拿到对应索引的文件名,不需要通过DataFrame来调用。

修正后的代码方案

其实还有更高效的写法:在读取每个CSV文件的时候就直接添加Timestamp列,不用等到后面再循环处理,这样代码更简洁,也不容易出错。

import glob
import os
import pandas as pd
import numpy as np

os.chdir("I:/INRIX and BeMobile/BeMobile/2017-03-13")
extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
tempList = []
runUpTo = 30

# 读取文件时直接添加Timestamp列
for idx, filename in enumerate(all_filenames[:runUpTo]):
    print(f'Currently in iteration {idx + 1} of {len(all_filenames[:runUpTo])}')
    temp = pd.read_csv(filename, sep=';', skiprows=1, header=None)
    temp.columns = ['Delete1','segmentID','Duration','Delete2']
    temp = temp[['segmentID','Duration']]
    temp = temp.sort_values('segmentID').reset_index(drop=True)  # 替代你的index重新赋值
    # 直接添加文件名列
    temp['Timestamp'] = filename
    tempList.append(temp)

如果坚持要保留你原来的两步写法(先读文件存列表,再循环加列),那修正后的循环部分应该是这样:

# 修正后的添加列循环
for i in range(len(tempList[:runUpTo])):
    tempList[i].is_copy = False
    # 直接用外部的all_filenames列表取对应文件名
    tempList[i]['Timestamp'] = all_filenames[i]

额外优化建议

  • 用enumerate遍历文件名和索引比用range(len(...))更直观,代码可读性更高。
  • 用reset_index(drop=True)替代temp.index = np.arange(len(temp)),这是Pandas更标准的重置索引方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 06:47:41