Reverse Part of an Array Using 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.

3 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])
2
>>> a = np.array([1,2,3,4,5,6])
>>> a[1:4] = a[3:0:-1]
>>> a
array([1, 4, 3, 2, 5, 6])

You can use the permutation matrices (that's the numpiest way to partially reverse an array).

a = np.array([1,2,3,4,5,6])
new_order_for_index = [1,4,3,2,5,6] # Careful: index from 1 to n !

# Permutation matrix
m = np.zeros( (len(a),len(a)) )
for index , new_index  in enumerate(new_order_for_index ):
    m[index ,new_index -1] = 1

print np.dot(m,a)
# np.array([1,4,3,2,5,6])
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest