python - numpy 数组 : IndexError: too many indices for array

标签 python numpy

这个有效:

>>> 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/

相关文章:

python - 基于区域的图像检测与状态验证

javascript - 将生成的 HTML 传递给 JavaScript

python - 如何在 Python 中插入二维曲线

python - 如何模拟在 with 语句中使用的 open (使用 Python 中的 Mock 框架)?

python - Django + PostgreSQL + DjangoRestFramework

python - 有没有办法检查针对 django 版本的功能弃用?

python - Numpy 沿轴应用并获取行索引

python - 如何计算 3d 数组的所有 24 次旋转?

python - 从2D numpy数组中删除特定行值的数组的快速方法

python - TypeError : dst is not a numpy array, 都不是标量 - 调整 jpg python 大小