Home > database >  How does NumPy in-place sort work on views?
How does NumPy in-place sort work on views?

Time:01-03

Could you please help me understand the output of these two sorting attempts:

Attempt 1

import numpy as np
a = np.array([1, 2, 3])
a[::-1].sort()
print(a)
# prints [3 2 1]

I somehow understand that a[::-1] is a view and hence sorting in place leads to descending order instead of the usual ascending order.

Attempt 2

import numpy as np
a = np.array([1, 2, 3])
a = a[::-1]
a.sort()
print(a)
# prints [1 2 3]

What has changed here? We are still operating on a view so why is the output different?

CodePudding user response:

Let's avoid the complications of "assigning back", and use a new variable name:

In [75]: x=np.array([1,2,3]); x1 = x[::-1]    
In [76]: x1, x1.base
Out[76]: (array([3, 2, 1]), array([1, 2, 3]))

In [77]: x1.sort()

In [78]: x1, x1.base
Out[78]: (array([1, 2, 3]), array([3, 2, 1]))

So x1 as been sorted in-place, and in the process that changes the base (which is still x).

In the one liner, x changes in the same way:

In [79]: x=np.array([1,2,3]); x[::-1].sort()
In [80]: x
Out[80]: array([3, 2, 1])

So the same thing happens in both cases. It's just obscured by the a=a[::-1] step.

CodePudding user response:

Interesting question. Have a look here:

>>> a = np.array([1, 2, 3])
>>> a = a[::-1]
>>> a
array([3, 2, 1])
>>> a.base
array([1, 2, 3])
>>> a.sort()
>>> a
array([1, 2, 3])
>>> a.base
array([3, 2, 1])

In your attempt 2, the base array is in fact sorted in reverse order, but since you reassigned back to a, and that's the one you're printing, you'll see a sorted version of the view, not the base.

  • Related