Reputation: 9893
I need to get the last four column data of a ndarray
, most of time code arr[:, -4:]
is ok, but if the array just has one dimension, this will throw IndexError: too many indices
.
My data is get with arr = np.loadtxt('test.txt')
, so if test.txt
has more than one line, like
0 1 2 3 4
0 10 20 30 40
everything is ok, but if test.txt
has just one line, like
0 1 2 3 4
this will return array([ 0, 1, 2, 3, 4])
, then arr[:, -4:]
will throw exception, because it should be arr[-4:]
, so how to make loadtxt
return array([[ 0, 1, 2, 3, 4]])
?
Upvotes: 6
Views: 4163
Reputation: 67427
Use the Ellipsis
(...
) instead of an empty slice
(:
) for your first index:
>>> 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
EDIT If you want the return to be 2D also for the single row case, then this should do the trick:
>>> np.atleast_2d(a[..., -4:])
array([[6, 7, 8, 9]])
Upvotes: 2