4

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 3

11

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Is this double slicing a[1:4][::-1] the proper pythonic way, or is there a solution using a single slice? Couldn't this be done simpler via a[3:0:-1]?
@Walter, yes that's what John Zwinck's answer does, but it is not as clear to the reader which elements are being selected.
5
>>> a = np.array([1,2,3,4,5,6])
>>> a[1:4] = a[3:0:-1]
>>> a
array([1, 4, 3, 2, 5, 6])

Comments

1

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 Comment

You can't throw code in a for loop and call it the numpiest.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.