简体   繁体   English

numpy数组:IndexError:数组的索引太多了

[英]numpy array: IndexError: too many indices for array

This works: 这有效:

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> a[: , 2]
array([ 3,  7, 11])

This doesn't 事实并非如此

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
>>> a[:,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

Why so ? 为什么这样 ?

Numpy ndarrays are meant for all elements to have the same length. Numpy ndarrays适用于所有元素具有相同的长度。 In this case, your second array doesn't contain lists of the same length, so it ends up being a 1-D array of lists, as opposed to a "proper" 2-D array. 在这种情况下,您的第二个数组不包含相同长度的列表,因此它最终是一个列表的一维数组,而不是“正确的”二维数组。

From the Numpy docs on N-dimensional arrays : 来自N维数组的Numpy文档:

An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. ndarray是具有相同类型和大小的项目的(通常是固定大小的)多维容器。

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
a.shape # (3,4)
a.ndim # 2

b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
b.shape # (3,)
b.ndim # 1

This discussion may be useful. 这个讨论可能有用。

The first array has shape (3,4) and the second has shape (3,). 第一个阵列具有形状(3,4),第二个阵列具有形状(3,)。 The second array is missing a second dimension. 第二个数组缺少第二个维度。 np.array is unable to use this input to construct a matrix (or array of similarly-lengthed arrays). np.array无法使用此输入来构造矩阵(或类似延长数组的数组)。 It is only able to make an array of lists. 它只能制作一系列列表。

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

>>> print(a)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

>>> print(type(a))
<class 'numpy.ndarray'>


>>> b = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])

>>> print(b)
[list([1, 2, 3, 4]) list([5, 6, 7, 8]) list([9, 10, 11])]

>>> print(type(b))
<class 'numpy.ndarray'>

So they are both Numpy arrays, but only the first can be treated as a matrix with two dimensions. 因此它们都是Numpy数组,但只有第一个可以被视为具有两个维度的矩阵。

It's simple to see what the problem is. 很容易看出问题所在。 Try, 尝试,

>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> a.shape

and then 接着

>>>a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11]])
>>> a.shape

and you will see the problem yourself, that in case two, shape is (3,).Hence the too many indices. 并且你会自己看到问题,如果是两个,形状是(3,)。因此索引太多了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM