【问题标题】:Index Error: Index out of bounds when using numpy in python索引错误:在 python 中使用 numpy 时索引超出范围
【发布时间】:2014-08-29 18:29:24
【问题描述】:

我的代码在我有小 CSV 数据时可以正常工作,但当我尝试通过它运行大 CSV 时出错。本质上,这段代码应该将 3 个 CSV 的数据放入 3 个单独的字典中,将这些字典组合成一个主字典,然后对字典执行算术运算。输入 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

【问题讨论】:

    标签: python csv numpy


    【解决方案1】:

    您的 csv 文件中的一行可能不包含 5 个元素,或者该行为空。 在您的逻辑中,我建议使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-09
      • 2016-04-17
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多