Machine
Machine

Reputation: 153

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]

Upvotes: 3

Views: 580

Answers (1)

mgilson
mgilson

Reputation: 309929

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()

Upvotes: 4

Related Questions