frongere
frongere

Reputation: 75

Inplace permutation of a numpy arrray

I have a quite large numpy array of one dimension for which I would like to apply some sorting on a slice inplace and also retrieve the permutation vector for other processing.

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

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

iperm = Vslice.argsort()

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

Subsidiary question : Why the following code does not modifies V as we are working on a view of V ?

Vslice = Vslice[iperm]

Best wishes !

François

Upvotes: 3

Views: 771

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77961

To answer your question of why assignment to view does not modify the original:

You need to change Vslice = Vslice[iperm] to Vslice[:] = Vslice[iperm] otherwise you are assigning a new value to Vslice rather than 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])

Upvotes: 3

Related Questions