数组索引过多:IndexError

97

我知道这类主题有很多,但它们都是针对非常简单的情况,比如3x3矩阵之类的东西,解决方案甚至无法适用于我的情况。所以我正在尝试绘制G关于l1(不是数字11,而是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
数组是从零开始的,一个有12个元素的数组中没有第12个索引。 - Padraic Cunningham
你尝试在 for data, color in zip(outputs_l1, colors): 后面加上 print data 来查看每一行数据的样子了吗?看起来它可能没有按照你预期的格式进行排列(你认为它应该是一个由14个元素组成的数组,对吧?但似乎有时只有12个元素)。 - zehnpaard
当我输入'print data'或'print outputs_l1'时,它会显示无效语法。而且有14个参数,所以最后两个将是#12和#13,这就是我为图表调用的内容。你在哪里看到只有12个实例?那是我的问题之一,我认为我已经解决了,但我可能错过了什么。 - Chris
你在使用Python 3.x吗?如果是的话,应该用print(data)代替。IndexError: index 12 is out of bounds for axis 1 with size 12说明数据行中某处仅包含12个元素。 - zehnpaard
3个回答

83

我认为问题已经在错误信息中给出,尽管它不是很容易发现:

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

“Too many indices” 意味着您提供了过多的索引值。由于您期望数据为二维数组,因此提供了 2 个值。Numpy 抱怨是因为 data 不是 2D 数组(它只是 1D 或者 None)。

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

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

print(data)

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


12

您收到的消息并非针对 Python 的默认异常:

对于一个新创建的 Python 列表,只有当索引不在范围内时才会抛出 IndexError 异常(即使文档也是如此)。

>>> 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,该库内部使用numpy来处理数组。在深入挖掘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不同的是,当索引不正确时,Numpy会引发IndexError,因为它支持多维数组。


-2
在将数据转换为列表之前,我先将数据转换为了列表。 data = list(data) data = np.array(data)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接