How do I make np.loadtxt return multidimensional arrays, even the file is only one size?
I need to get the last four columns of data ndarray
, most of the time code arr[:, -4:]
is fine, but if the array only has one dimension, this will throw IndexError: too many indices
.
My data is obtained from arr = np.loadtxt('test.txt')
, so if it test.txt
has more than one row like
0 1 2 3 4
0 10 20 30 40
everything is fine, but if it test.txt
has only one line like
0 1 2 3 4
this will return array([ 0, 1, 2, 3, 4])
, then it arr[:, -4:]
will throw an exception because it should be arr[-4:]
, so how to do loadtxt
return array([[ 0, 1, 2, 3, 4]])
?
source to share
Use Ellipsis
( ...
) instead of 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 2D also for the single line case, then this should do the trick:
>>> np.atleast_2d(a[..., -4:])
array([[6, 7, 8, 9]])
source to share