Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy assigning to slice, when is the array copied

Tags:

python

numpy

So with numpy arrays assigning one to another just copies the reference: i.e.

import numpy as np
x = np.array([5,8])
y = x 
y += 1
x
Out: array([6, 9])

And if I want a deep copy then I should use x.copy(). And the same is true when taking a view out of a higher dimensional array, e.g.

A=np.array([[4,10],[8,1]])
b=A[:,1]
b+=1
A
Out: array([[ 4, 11],
            [ 8,  2]])

And the other way round (continuing from above):

A[:,1]=b
b
Out: array([11,  2])
b+=1
A
Out: array([[ 4, 12],
            [ 8,  3]])

So up to here everything is working consistently. But now if I carry on and do:

A[:,0] = b
A
Out: array([[12, 12],
            [ 3,  3]])
b
Out: array([12,  3])
b+=1
A
Out: array([[12, 13],
            [ 3,  4]])

What I don't understand is why the first column stays the same and the other doesn't? Why does the second column continue to point to the b array? Is there any rule for deciding when an array will be deep copied on assignment?

like image 853
jay--bee Avatar asked Mar 24 '15 22:03

jay--bee


People also ask

How does NumPy array slicing work?

Slicing arrays Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .

Does NumPy array make a copy?

copy() Function. By using numpy. copy() function you can create an array copy of the given object. In the below example, the given Numpy array 'array' is copied to another array 'copy_array' using copy() function.

Does reshape make a copy?

With a compatible order, reshape does not produce a copy.

What is the difference between copy and view in NumPy?

The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array. The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.


1 Answers

When you are doing

b=A[:,1]

it is creating a reference to the underlying array. But in this case

A[:,0] = b

only values are copied.As a result in the last statement first column remains unchanged while second column which is still being referenced by b changes. Take a look at this

like image 108
avinash pandey Avatar answered Sep 21 '22 15:09

avinash pandey