3

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]
7
  • y = x[:] should work Commented Jan 12, 2016 at 22:04
  • @Arman Thanks but y = x[:] is the same as y=x Commented Jan 12, 2016 at 22:11
  • y = x[:] is likey = x.copy() Commented Jan 12, 2016 at 22:13
  • @Arman I'm using python3, it might work on other versions of python. BTW x is a numpy array not a list. Commented Jan 12, 2016 at 22:15
  • 1
    @Arman -- I'm not sure about that. First, x[:] will only have a chance at working for 1D arrays. Second, x[:] creates a view in numpy. I think that this can create a copy under some circumstances, but it frequently doesn't. . . Commented Jan 12, 2016 at 22:32

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! y = x and y = x[:] do NOT work; y is x and y = x.copy() both work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.