如何让np.loadtxt返回多维数组,即使文件只有一维?

时间:2015-01-09 07:42:45

标签: python arrays numpy multidimensional-array

我需要获取ndarray的最后四列数据,大部分时间代码arr[:, -4:]都可以,但如果数组只有一个维度,则会抛出IndexError: too many indices

我的数据来自arr = np.loadtxt('test.txt'),因此如果test.txt有多行,例如

0 1 2 3 4
0 10 20 30 40

一切正常,但如果test.txt只有一行,例如

0 1 2 3 4

这将返回array([ 0, 1, 2, 3, 4]),然后arr[:, -4:]会抛出异常,因为它应该是arr[-4:],那么如何让loadtxt返回array([[ 0, 1, 2, 3, 4]])

2 个答案:

答案 0 :(得分:3)

刚刚找到它here

您可以要求它至少有2个维度:

arr = np.loadtxt('test.txt', ndmin=2)

答案 1 :(得分:2)

使用Ellipsis...)代替空slice:)作为您的第一个索引:

>>> a = np.arange(30).reshape(3, 10)
>>> a[:, -4:]
array([[ 6,  7,  8,  9],
       [16, 17, 18, 19],
       [26, 27, 28, 29]])
>>> a[..., -4:]  # works the same for the 2D case
array([[ 6,  7,  8,  9],
       [16, 17, 18, 19],
       [26, 27, 28, 29]])

>>> a = np.arange(10)
>>> a[..., -4:]  # works also in the 1D case
array([6, 7, 8, 9])
>>> a[:, -4:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for array

编辑如果您希望单行情况下返回也是2D,那么这应该可以解决问题:

>>> np.atleast_2d(a[..., -4:])
array([[6, 7, 8, 9]])