1

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]
Pickniclas
  • 349
  • 1
  • 8
  • so how does your 2D array look like? if it is something like `np.arange(2000).reshape(2,1000)`, you could do `arr[0][:500:-1]` for axis 0 – FObersteiner Aug 01 '19 at 07:05

2 Answers2

3

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])
Mark
  • 90,562
  • 7
  • 108
  • 148
  • By the way, `n[:10:-1]` also works. The start `-1` is redundant. – iz_ Aug 01 '19 at 06:42
  • 2
    Thanks @iz_. That's a good tip; I didn't know that. For some reason the lack of explicitness bothers me — but maybe jut takes some getting used to. – Mark Aug 01 '19 at 06:43
  • 1
    I guess it's a trade-off between being explicit and being concise. Personally, I prefer `n[:10:-1]` because I can look at it and immediate see: `10` - 10 elements, `-1` - reverse. Anyway, it's pretty opinion based. +1 – iz_ Aug 01 '19 at 06:47
0

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])
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52