首页 > 解决方案 > 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

标签: pythonpython-3.xcsv

解决方案


推荐阅读