Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array slicing: access first two elements in reverse order running for loop

Suppose I have 1D array of length 10:

A = np.arange(10)

I would like to access 2 elements at a time and reverse them. After that A would look like this:

np.array([1,0,3,2,5,4,7,6,9,8])

I do this in for loop:

for i in range(5):
    A[2*i:2*i+2] = A[2*i+1:2*i-1:-1]

This solution works for i!=0. Is it possible to get desired output for ALL elements, without special case for i?

*I used 1D just as an example. My actual array is 2D, with y and x coordinates as rows. cv2.fitEllipse and cv.drawContours require array where x and y are columns ((2,n)->(n,1,2)). I have to change the shape of my array and reverse the order (and I would like to do this in 1 operation).

like image 804
recodeFuture Avatar asked Mar 14 '26 00:03

recodeFuture


1 Answers

You could do something like this:

>>> arr = np.arange(10)
>>> arr.reshape(arr.size/2, 2)[:,::-1].flatten()
array([1, 0, 3, 2, 5, 4, 7, 6, 9, 8])

For in-place modification:

>>> arr = np.arange(10)
>>> arr[::2], arr[1::2] = arr[1::2], arr[::2].copy()
>>> arr
array([1, 0, 3, 2, 5, 4, 7, 6, 9, 8])

Calling .copy() is required because by the time Python will reach arr[1::2] on LHS the items at arr[::2] are already modified.

like image 62
Ashwini Chaudhary Avatar answered Mar 16 '26 15:03

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!