Python IndexError:数组的索引太多
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28036812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IndexError: too many indices for array
提问by Chris
I know there is a ton of these threads but all of them are for very simple cases like 3x3 matrices and things of that sort and the solutions do not even begin to apply to my situation. So I'm trying to graph G versus l1 (that's not an eleven, but an L1). The data is in the file that I loaded from an excel file. The excel file is 14x250 so there are 14 arguments, each with 250 data points. I had another user (shout out to Hugh Bothwell!) help me with an error in my code, but now another error has surfaced.
我知道有很多这样的线程,但它们都是针对非常简单的情况,比如 3x3 矩阵和类似的东西,而且这些解决方案甚至不适用于我的情况。所以我试图绘制 G 与 l1 的关系图(那不是 11,而是 L1)。数据位于我从 excel 文件加载的文件中。excel 文件是 14x250,所以有 14 个参数,每个参数有 250 个数据点。我有另一个用户(向 Hugh Bothwell 大喊!)帮助我解决代码中的错误,但现在又出现了另一个错误。
So here is the code in question:
所以这是有问题的代码:
# 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)
After running the entire program, I recieve the error message:
运行整个程序后,我收到错误消息:
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
and before I ran into that problem, I had another involving the line a few below the one the above error message refers to:
在我遇到这个问题之前,我有另一个涉及上面错误消息所指的那一行下面的几行:
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
I understand the first error, but am just having problems fixing it. The second error is confusing for me though. My boss is really breathing down my neck so any help would be GREATLY appreciated!
我理解第一个错误,但只是在修复它时遇到问题。不过,第二个错误让我感到困惑。我的老板真的在我的脖子上呼吸,所以任何帮助将不胜感激!
回答by J Richard Snape
I think the problem is given in the error message, although it is not very easy to spot:
我认为问题是在错误消息中给出的,虽然不是很容易发现:
IndexError: too many indices for array
xs = data[:, col["l1" ]]
'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data
is not 2D (it's either 1D or None).
“索引太多”意味着您提供了太多索引值。您已经给出了 2 个值,因为您希望数据是一个二维数组。Numpy 抱怨是因为data
它不是 2D(它是 1D 或 None)。
This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None)
does not throw an Error
, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile
function.
这有点猜测 - 我想知道您传递给 loadfile() 的文件名之一是指向空文件还是格式错误的文件?如果是这样,你可能会得到一个返回的数组,它要么是一维的,要么是空的(np.array(None)
不抛出Error
,所以你永远不会知道......)。如果你想防止这种失败,你可以在你的loadfile
函数中插入一些错误检查。
I highly recommend in your for
loop inserting:
我强烈建议在您的for
循环中插入:
print(data)
This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1
list (i.e. one file) that is giving the issue.
这将适用于 Python 2.x 或 3.x,并且可能会揭示问题的根源。您可能会发现只有outputs_l1
列表中的一个值(即一个文件)导致了问题。
回答by u1860929
The message that you are getting is not for the default Exception of Python:
您收到的消息不适用于 Python 的默认异常:
For a fresh python list, IndexError
is thrown only on index not being in range (even docssay so).
对于新的 python 列表,IndexError
仅在索引不在范围内时抛出(甚至文档也这么说)。
>>> l = []
>>> l[1]
IndexError: list index out of range
If we try passing multiple items to list, or some other value, we get the TypeError
:
如果我们尝试将多个项目传递给列表或其他一些值,我们会得到TypeError
:
>>> l[1, 2]
TypeError: list indices must be integers, not tuple
>>> l[float('NaN')]
TypeError: list indices must be integers, not float
However, here, you seem to be using matplotlib
that internally uses numpy
for handling arrays. On digging deeper through the codebase for numpy
, we see:
但是,在这里,您似乎正在使用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;
}
where, the unpack method will throw an error if it the size of the index is greater than that of the results.
其中,如果索引的大小大于结果的大小, unpack 方法将抛出错误。
So, Unlike Python which raises a TypeError
on incorrect Indexes, Numpy raises the IndexError
because it supports multidimensional arrays.
因此,与 PythonTypeError
在不正确的索引上引发 a 不同,Numpy 引发 是IndexError
因为它支持多维数组。