如何解决IndexError:列表索引超出范围?

时间:2020-09-09 10:33:37

标签: python numpy matplotlib

我是python的新手,正在尝试为unit赋值,但是我似乎无法克服索引错误。我已经尝试了所有可以想到的东西以及可以在互联网上找到的所有东西,但我不知道出了什么问题。

这是我要开始工作的代码。

两个文件都在同一文件夹中。

错误消息不断出现在“ hn.append(row [1])”上

Undefined method LoginController::username

这是完整的错误消息

import numpy as np    
import csv           
#import the ploting library bits
from mpl_toolkits.mplot3d import Axes3D   # for our 3-D plots
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

lr = []    
hn = []
ac = []

with open("vert.csv") as csvDataFile:   
    csvReader = csv.reader(csvDataFile)  
    for row in csvReader:
        lr.append(row[0])
        hn.append(row[1])
        ac.append(row[2])

x = np.asfarray(lr[1:])
y = np.asfarray(hn[1:])
z = np.asfarray(ac[1:])*100   

ax.scatter(x, y, z, c='r', marker='o')    # plot the x,y,z, data points

ax.set_ylabel('LR')    # axis labels
ax.set_xlabel('NH')
ax.set_zlabel('Performance')

plt.show()

1 个答案:

答案 0 :(得分:0)

由于已通过确保CSV文件中至少包含3列来解决IndexError,从而克服了ValueError,因此获得了lrhn和,ac转换为浮点数。它们当前是字符串,而您需要使用浮点数或整数:

lr1 = [float(x) for x in lr] #create a list lr1 with same elements as lr but elements type is float, using list comprehension
hn1 = [float(y) for y in hn] # same operation for hn
ac1 = [float(x) for x in ac] # same operation for ac
x = np.asfarray(lr1[1:])
y = np.asfarray(hn1[1:])
z = np.asfarray(ac1[1:])*100