Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python numpy argsort issue

First I generated a random 1d array x, then I generated array y by swapping elements of x.

Now y is a permutation of x, in principle, if I apply numpy argsort, I should get different results, as it turned out, it was not the case.

Here are my python codes,

import numpy as np
x = np.random.random(10)
print(x)
y = x
y[0], y[1] = x[1], x[0]
y[3], y[4] = x[4], x[3]
print(y)

Then I got

[ 0.818  0.99   0.291  0.608  0.773  0.232  0.041  0.136  0.645  0.94 ]
[ 0.99   0.818  0.291  0.773  0.608  0.232  0.041  0.136  0.645  0.94 ]

Now

print(np.argsort(x))
print(np.argsort(y))

I got

[6 7 5 2 4 8 3 1 9 0]
[6 7 5 2 4 8 3 1 9 0]
like image 345
Machine Avatar asked Sep 21 '26 17:09

Machine


1 Answers

When you do:

y = x

You alias y and x. They're the same object which you can see by issuing the following statement

y is x  # True

Instead, you probably want:

y = x.copy()
like image 138
mgilson Avatar answered Sep 23 '26 06:09

mgilson



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!