How do I change a NumPy array in place?

Is there any efficient way to flip NumPy in place ?

Note. I am NOT looking for a reverse look. I want the array to be really reversed.

+3


source to share


1 answer


This is inelegant, but if in-place is the most important factor and runtime is not that important (since multiple slicing would be far away - do an iterative approach), you can always swap the indices to the left and right of the array while the indices converge:

def reverse(arr):
    ln = arr.shape[0]
    lidx, ridx = 0, ln - 1

    while lidx < ridx:
        rtmp = arr[ridx]
        arr[ridx] = arr[lidx]
        arr[lidx] = rtmp
        lidx += 1
        ridx -= 1

    return arr

      

This will work for arrays of both odd and even length. Evenly:

>>> reverse(np.arange(4))
array([3, 2, 1, 0])

      



Odd:

>>> reverse(np.arange(5))
array([4, 3, 2, 1, 0])

      

And to prove it locally:

>>> y = np.arange(6)
>>> x = reverse(y)
>>> x is y
True

      

0


source







All Articles