Numpy in place permutation

I have a fairly large one dimension numpy array for which I would like to apply some sort of slice-in-place sorting and also get the permutation vector for other processing.

However, the ndarray.sort () method (which is inplace) does not return this vector, and I can use the ndarray.argsort () method to get the permutation vector and use it to permute the slice. However, I cannot figure out how to do this locally.

Vslice = V[istart:istop]  # This is a view of the slice

iperm = Vslice.argsort()

V[istart:istop] = Vslice[iperm]  # Not an inplace operation...

      

Ancillary question: why does the following code not modify V as we are working on the V representation?

Vslice = Vslice[iperm]

      

Regards!

Francois

+3


source to share


1 answer


To answer the question why the view assignment doesn't change the original:

You need to change Vslice = Vslice[iperm]

to Vslice[:] = Vslice[iperm]

, otherwise you are assigning a new value Vslice

instead of changing the values ​​inside Vslice

:



>>> a = np.arange(10, 0, -1)
>>> a
array([10,  9,  8,  7,  6,  5,  4,  3,  2,  1])
>>> b = a[2:-2]
>>> b
array([8, 7, 6, 5, 4, 3])
>>> i = b.argsort()
>>> b[:] = b[i]  # change the values inside the view
>>> a            # note `a` has been sorted in [2:-2] slice
array([10,  9,  3,  4,  5,  6,  7,  8,  2,  1])

      

+3


source







All Articles