循环每个 csv 文件的代码时出现元组错误或错误

问题描述 投票:0回答:1
T = ('twang10_1.csv','twang10_2.csv','twang10_3.csv','twang12_1.csv','twang12_2.csv','twang12_3.csv','twang14_1.csv','twang14_2.csv','twang14_3.csv','1000.csv','500.csv','voice.csv')

file_in = []

for item in T:
    file_in.append(open(item, 'r'))

y = T[1].to_numpy() for this line i get the error

对于变量 T 中的每个 csv 文件,我需要为每个文件生成一个图表。但我得到元组必须是整数错误。 说:元组索引必须是整数或切片,而不是 str

python integer tuples slice
1个回答
0
投票

你在这里调用了错误的列表。要根据 CSV 中的数据制作图表,您需要调用 file_in[1](列表中的第二项)而不是 T[1],因为这只是一个带有 CSV 名称的字符串。

T = ('twang10_1.csv','twang10_2.csv','twang10_3.csv','twang12_1.csv','twang12_2.csv','twang12_3.csv','twang14_1.csv','twang14_2.csv','twang14_3.csv','1000.csv','500.csv','voice.csv')

file_in = []

for item in T:
    file_in.append(open(item, 'r'))

y = file_in[1].to_numpy() #for this line i get the error

这将调用文件数据,而不是文件名。

import numpy as np

T = ('twang10_1.csv','twang10_2.csv','twang10_3.csv','twang12_1.csv','twang12_2.csv','twang12_3.csv','twang14_1.csv','twang14_2.csv','twang14_3.csv','1000.csv','500.csv','voice.csv')

numpy_list= []

for item in T:
    numpy_list.append(np.loadtxt(item, delimiter=","))

#Every item in numpy_list would then be a numpy array

来自 CSV youtube 视频的 NumPy 加载数组:https://youtu.be/Z2unXTrGp04

基于评论讨论:

import numpy as np 
#import pandas as pd #Pandas is not used here, not needed
import matplotlib.pyplot as plt 
#from scipy import signal #not sure if you need this later on, but it's not needed in this snippit. 

sampling_rate=5000
sampling_time=0.1 

T = ('twang10_1.csv','twang10_2.csv','twang10_3.csv','twang12_1.csv','twang12_2.csv','twang12_3.csv','twang14_1.csv','twang14_2.csv','twang14_3.csv','1000.csv','500.csv','voice.csv')

csv_data = [] 

for item in T: 
    csv_data.append(np.loadtxt(item, delimiter=","))

y = csv_data[1] 



y_av = np.average(y) 

start_value = np.argmax(y) 

end_value = int(start_value+sampling_time*sampling_rate) 
#y = y - y_av 
#you can't subtract a value from a list of values

#y = y[start_value:end_value] 
#not needed

x = np.linspace(0, len(y)/sampling_rate, len(y)) 

fig, ax1 = plt.subplots() #fig is not being used, can be left out

plot = ax1.scatter(x,y,s=1,color='red') #plt can't be set to a value as it's a module import, can't use it in multiple ways

ax1.set_xlabel("time (s)") 

ax1.set_ylabel("amplitude")

我相信这对你有用,我已经在代码的注释中解释了我改变了什么以及为什么。

© www.soinside.com 2019 - 2024. All rights reserved.