索引错误:使用numpy时索引超出范围

0 投票
1 回答
509 浏览
提问于 2025-04-18 21:12

我有一段代码,当我处理小的CSV数据时运行得很好,但当我试图处理大的CSV文件时就出错了。简单来说,这段代码是用来把三份CSV的数据放进三个不同的字典里,然后把这三个字典合并成一个主字典,最后对这个主字典进行一些数学运算。输入的CSV文件大概长这样:

time   A  B  C  D
  0    3  4  6  4
.001   4  6  7  8 
.002   4  6  7  3 

我使用的代码如下。错误发生在第47行和第65行,那时我正试图对字典进行数学运算。对于为什么会出现这个问题,任何解释都非常感谢。

import numpy

Xcoord = {}
time = []
with open ('Nodal_QuardnetsX2.csv', 'r') as f:
    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Xcoord[values[0]] = map(float, values[1:])
        time.append(values[0])

Ycoord = {}
with open ('Nodal_QuardnetsY2.csv', 'r') as f:

    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Ycoord[values[0]] = map(float, values[1:])

Zcoord = {}
with open ('Nodal_QuardnetsZ2.csv', 'r') as f:
    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Zcoord[values[0]] = map(float, values[1:])

# Create a master dictionary of the form {'key':[[x, y, z], [x, y, z]}   
CoordCombo = {}
for key in Xcoord.keys():
    CoordnateList = zip(Xcoord[key], Ycoord[key], Zcoord[key])
    CoordCombo[key] = CoordnateList

counter = 0
keycount1 = 0
keycount2 = 0.001
difference = []
NodalDisplacements = {}

#Find the difference between the x, y, and z quardnets relative to that point in time
while keycount2 <= float(values[0]): 
        Sub = numpy.subtract(CoordCombo[str(keycount2)][counter], CoordCombo[str(keycount1)][counter])    
        counter = counter + 1
        difference.append(Sub)
        NodalDisplacements[keycount1] = Sub
        keycount1 = keycount1 + 0.001
        keycount2 = keycount2 + 0.001

counter = 0
keycount3 = 0
keycount4 = 0.001

Sum = []
breakpoint = float(values[0])-0.001

while keycount4 <= breakpoint:
    Add = numpy.sum(NodalDisplacements[keycount4][counter], NodalDisplacements[keycount3][counter])
    Sum.append(Add)
    keycount3 = keycount3 + 0.001
    keycount4 = keycount4 + 0.001
    counter = counter + 1
    if counter == 2:
        counter = 0
print Sum

1 个回答

0

可能是你的CSV文件中的某一行没有5个元素,或者那一行是空的。根据你的逻辑,我建议使用

for line in f:
   line = line.strip()
   if not line: continue
   if len(values) != N_COLS: continue # or error...
   # other ...

撰写回答