python - TypeError:列表索引必须是整数或切片,而不是 str - Python
问题描述
我正在尝试对多个 .csv 文件进行分析。我有一个包含 500 多个 .csv 的文件夹,我想从每个文件夹中提取一些信息,然后使用我提取的信息创建一个唯一的 .csv。我正在考虑打开一个文件,执行计算(例如,提取 RMS、最大值、最小值),使用 append() 方法将这些值存储在一个新的 DataFrame 中,然后它们会移动到下一个文件。不幸的是,截至目前,我被标题中的问题所困扰。在分析输出中的文件时,出现错误“TypeError:列表索引必须是整数或切片,而不是 str”
import os
import pandas as pd
import matplotlib.pyplot as plt
new_df=[]
temp_cols=['Hour','Minute','Second','x_second','RTD_sensor']
### Set your path to the folder containing the .csv files
PATH = 'C:\\Users\\UserName\\Documents\\python\\NASA\\FEMTOBearingDataSet\\Training_set\\Bearing1_1\\temp\\' # Use your path
### Fetch all files in path
fileNames = os.listdir(PATH)
### Filter file name list for files ending with .csv
fileNames = [file for file in fileNames if '.csv' in file]
### Loop over all files
for file in fileNames:
### Read .csv file and append to list
df = pd.read_csv(PATH + file, sep=',', header=None, names=temp_cols, index_col = None)
for column in range(0,len(temp_cols)):
new_df['Mean'].append(df.iloc[:,column].mean())
new_df.head()
我收到的错误消息如下:
TypeError Traceback (most recent call last)
<ipython-input-55-4a40c157922b> in <module>()
19 df = pd.read_csv(PATH + file, sep=',', header=None, names=temp_cols, index_col = None)
20 for column in range(0,len(temp_cols)):
---> 21 new_df['Mean'].append(df.iloc[:,column].mean())
22
23 ### Create line for every file
TypeError: list indices must be integers or slices, not str
解决方案
推荐阅读
- hana - 使用 SAP HANA CDS 文件时,STRING_AGG 不是可识别的内置函数名称
- javascript - 如何获取已动态给出 ID 的元素的 ID?
- c# - 检查重复
- python - 将纪元时间转换为本地时间
- python - 在 pyspark 中调整二项式 Logistic 回归参数;
- c# - 如何连接远程 RabbitMQ 服务器
- ios - Expo CLI 2.0 运行 ios 模拟器时出错
- java - 从 Pie 到 Nougat 和 Oreo 的兼容性问题
- java - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int com.xxHelper.SharedPref.GetInt(java.lang.String)”
- r - 为类别分配编号