Reputation: 359
I have a numpy array from 0 to 999 and I would like to make a slice that runs from the last element in the list (999) to the one in the middle (500).
test[500:][::-1] works but if I have a two dimensional array and I only want to do so along the zeroth axis it doesn't work because it also reverses the second axis.
import numpy as np
test = np.arange(1000)
test[500:][::-1]
Upvotes: 1
Views: 1103
Reputation: 92440
You can slice from -1
to your stop index with a step of -1
:
> import numpy as np
> n = np.arange(20)
> n[-1:10:-1]
array([19, 18, 17, 16, 15, 14, 13, 12, 11])
> # or (thanks iz_)
> n[:10:-1]
array([19, 18, 17, 16, 15, 14, 13, 12, 11])
Upvotes: 3
Reputation: 15872
You can use np.flip()
>>> x = np.arange(20)
>>> x
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19])
>>> np.flip(x)
array([19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3,
2, 1, 0])
Upvotes: 0