Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse part of an array using NumPy

Tags:

python

numpy

I am trying to use array slicing to reverse part of a NumPy array. If my array is, for example,

a = np.array([1,2,3,4,5,6])

then I can get a slice b

b = a[::-1]

Which is a view on the original array. What I would like is a view that is partially reversed, for example

1,4,3,2,5,6

I have encountered performance problems with NumPy if you don't play along exactly with how it is designed, so I would like to avoid "fancy" indexing if it is possible.

like image 344
Greg Reynolds Avatar asked Oct 17 '25 18:10

Greg Reynolds


2 Answers

If you don't like the off by one indices

>>> a = np.array([1,2,3,4,5,6])
>>> a[1:4] = a[1:4][::-1]
>>> a
array([1, 4, 3, 2, 5, 6])
like image 92
John La Rooy Avatar answered Oct 20 '25 07:10

John La Rooy


>>> a = np.array([1,2,3,4,5,6])
>>> a[1:4] = a[3:0:-1]
>>> a
array([1, 4, 3, 2, 5, 6])
like image 25
John Zwinck Avatar answered Oct 20 '25 08:10

John Zwinck