当我尝试像这样只获取数组的第一个元素时
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/