IndexError:数组的索引太多了

时间:2015-01-20 02:28:24

标签: python excel csv error-handling indexing

我知道有很多这些线程,但它们都是针对非常简单的情况,例如3x3矩阵和类似的东西,解决方案甚至不适用于我的情况。所以我试图将G与l1(这不是十一,而是一个L1)进行对比。数据位于我从excel文件加载的文件中。 excel文件是14x250,因此有14个参数,每个参数有250个数据点。我有另一个用户(向Hugh Bothwell大声喊叫!)帮助我在代码中出错,但现在又出现了另一个错误。

所以这是有问题的代码:

# format for CSV file:
header = ['l1', 'l2', 'l3', 'l4', 'l5', 'EI',
      'S', 'P_right', 'P1_0', 'P3_0',
      'w_left', 'w_right', 'G_left', 'G_right']

def loadfile(filename, skip=None, *args):
    skip = set(skip or [])
    with open(filename, *args) as f:
        cr = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
        return np.array(row for i,row in enumerate(cr) if i not in skip)
#plot data
outputs_l1 = [loadfile('C:\\Users\\Chris\\Desktop\\Work\\Python Stuff\\BPCROOM - Shingles analysis\\ERR analysis\\l_1 analysis//BS(1) ERR analysis - l_1 - P_3 = {}.csv'.format(p)) for p in p3_arr]

col = {name:i for i,name in enumerate(header)}

fig = plt.figure()
for data,color in zip(outputs_l1, colors):
    xs  = data[:, col["l1"     ]]
    gl = data[:, col["G_left" ]] * 1000.0    # column 12
    gr = data[:, col["G_right"]] * 1000.0    # column 13
    plt.plot(xs, gl, color + "-", gr, color + "--")
for output, col in zip(outputs_l1, colors):
    plt.plot(output[:,0], output[:,11]*1E3, col+'--')
plt.ticklabel_format(axis='both', style='plain', scilimits=(-1,1))
plt.xlabel('$l1 (m)$')
plt.ylabel('G $(J / m^2) * 10^{-3}$')
plt.xlim(xmin=.2)
plt.ylim(ymax=2, ymin=0)

plt.subplots_adjust(top=0.8, bottom=0.15, right=0.7)

运行整个程序后,我收到错误消息:

Traceback (most recent call last):
  File "C:/Users/Chris/Desktop/Work/Python Stuff/New Stuff from Brenday 8 26 2014/CD_ssa_plot(2).py", line 115, in <module>
    xs  = data[:, col["l1"     ]]
IndexError: too many indices for array

在我遇到这个问题之前,我有另一个涉及上面错误消息引用的一行以下的行:

Traceback (most recent call last): File "FILE", line 119, in <module> 
gl = data[:, col["G_left" ]] * 1000.0 # column 12 
IndexError: index 12 is out of bounds for axis 1 with size 12

我理解第一个错误,但我只是在修复它时遇到了问题。第二个错误让我感到困惑。我的老板真的在我的脖子上呼吸,所以任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:46)

我认为问题出现在错误信息中,尽管发现它并不容易:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

&#39;索引太多&#39;意味着你给出了太多的索引值。您已经给出了2个值,因为您希望数据是2D数组。 Numpy抱怨,因为data不是2D(它是1D或无)。

这是一个猜测 - 我想知道你传递给loadfile()的文件名之一是指向空文件还是格式错误的文件?如果是这样,你可能会得到一个返回的数组,它是1D,甚至是空的(np.array(None)不会抛出Error,所以你永远不会知道......)。如果您想防止此失败,可以在loadfile函数中插入一些错误检查。

我强烈建议您在for循环插入:

print(data)

这将在Python 2.x或3.x中运行,并可能揭示问题的根源。您可能会发现它只是您outputs_l1列表中的一个值(即一个文件)。

答案 1 :(得分:2)

您收到的消息不是针对Python的默认异常:

对于新的python列表,仅在索引不在范围内时抛出IndexError(即使docs也是如此)。

>>> l = []
>>> l[1]
IndexError: list index out of range

如果我们尝试将多个项目或其他值传递给列表,则会得到TypeError

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

但是,在这里,您似乎正在使用matplotlib that internally uses numpy来处理数组。在深入研究codebase for numpy时,我们看到:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

其中,如果索引大小大于结果大小,则unpack方法将引发错误。

因此,与Python在不正确的索引上引发TypeError的情况不同,Numpy会引发IndexError,因为它支持多维数组。

相关问题