0

I am having this unusual problem with shuffling arrays in numpy

arr = np.arange(9).reshape((3, 3))
print "Original constant array"
print arr
new_arr=arr
for i in range(3):        
    np.random.shuffle(new_arr)
    print "Obtained constant array"
    print arr
    print "randomized array"
    print new_arr

arr is my original array which I kept as such and created new array new_arr for further computation. But the code is showing this output

Original constant array
[[0 1 2]
 [3 4 5]
 [6 7 8]]
Obtained constant array
[[6 7 8]
 [0 1 2]
 [3 4 5]]
randomized array
[[6 7 8]
 [0 1 2]
 [3 4 5]]

I only wants to randomize new_arr and not arr. why this is happening and how to prevent arr from shuffling?

Eka
  • 14,170
  • 38
  • 128
  • 212
  • "created new array `new_arr`" - no you didn't. `new_arr=arr` doesn't make a new array. See https://nedbatchelder.com/text/names.html (but slicing works a bit differently between lists and NumPy arrays, so don't try to apply the parts about slicing to NumPy arrays). – user2357112 Apr 29 '17 at 15:54
  • You probably need to create a deep copy. See [numpy array assignment problem](http://stackoverflow.com/questions/3059395/numpy-array-assignment-problem) for the background. – roganjosh Apr 29 '17 at 15:55

2 Answers2

1

Use

new_arr = np.copy(arr)

instead of

new_arr = arr

When you do new_arr=arr you basically create a reference new_arr for your array arr


for example (Taken from numpy copy docs):

Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)

Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
JkShaw
  • 1,927
  • 2
  • 13
  • 14
1

When you say new_arr=arr, it copies the reference--it does not do a deep copy. Then when you change arr, it changes new_arr too.

Try new_arr = np.copy(arr). That should work.

Alex L
  • 1,114
  • 8
  • 11