python - IndexError : too many indices. 1 行 2 列的 Numpy 数组

标签 python arrays numpy

当我尝试像这样只获取数组的第一个元素时

import numpy

a = numpy.array([1,2])

a[:,0]

我收到这个错误

---------------------------------------------------------------------------
 IndexError                                Traceback (most recent call last)
<ipython-input-3-ed371621c46c> in <module>()
----> 1 a[:,0]

IndexError: too many indices

我想找到一种方法来做到这一点,同时仍然使用切片,因为完整的代码打开并使用 numpy.loadtxt() 读取许多不同的文件,所有文件都有两列,从 1 到一些不等N.

最佳答案

您的数组a = numpy.array([1,2]) 只有一个 维度:它的形状是(2,) .但是,您的切片 a[:,0] 指定了两个 维度的选择。这会导致 NumPy 引发错误。

要从 a 中获取第一个元素,您只需编写 a[0](此处仅选择一个维度)。


看着你的other question ,如果您想确保语法 a[:,0] 始终有效,您可以确保 a 始终具有两个维度。使用 np.loadtxt 加载数组时,使用 ndmin 参数,例如:

np.loadtxt(F, skiprows=0, ndmin=2)

关于python - IndexError : too many indices. 1 行 2 列的 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199585/

相关文章:

arrays - 如何预处理整数数组以找到 O(1) 中任意子数组的平均值?

python - 遍历类对象数组 VS 包含数组的类对象

python - 无法使用发布请求从网页中获取某些内容

python - 根据特定月份选择 xarray/pandas 索引

python - 两个 Pandas 数据框的联合

javascript - 如何将对象迭代到平面列表中 - react native ?

c - 从字符数组进行浮点检查以进行限制,字符检查正面和背面

python - numpy 数组 : replace nan values with average of columns

python - 缩放 numpy 数组中的图像无法撤消

Python类: TypeError: 'NoneType' object is not callable