这个有效:
>>> a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> a[: , 2]
array([ 3, 7, 11])
这不是
>>> 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
为什么会这样?
最佳答案
Numpy ndarrays 意味着所有元素都具有相同的长度。在这种情况下,您的第二个数组不包含相同长度的列表,因此它最终成为列表的一维数组,而不是“适当的”二维数组。
来自 N-dimensional arrays 上的 Numpy 文档:
An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.
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可能会有用。
关于python - numpy 数组 : IndexError: too many indices for array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733704/