Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of arr[:] in assignment in numpy?

I occasionally use numpy, and I'm trying to become smarter about how I vectorize operations. I'm reading some code and trying to understand the semantics of the following:

arr_1[:] = arr_2

In this case,

I understand that in arr[:, 0], we're selecting the first column of the array, but I'm confused about what the difference is between arr_1[:] = arr_2 and arr_1 = arr_2

like image 528
Alex Alifimoff Avatar asked Mar 01 '16 03:03

Alex Alifimoff


2 Answers

Your question involves a mix of basic Python syntax, and numpy specific details. In many ways it is the same for lists, but not exactly.

arr[:, 0] returns the 1st column of arr (a view), arr[:,0]=10 sets the values of that column to 10.

arr[:] returns arr (alist[:] returns a copy of a list). arr[:]=arr2 performs an inplace replacement; changing the values of arr to the values of arr2. The values of arr2 will be broadcasted and copied as needed.

arr=arr2 sets the object that the arr variable is pointing to. Now arr and arr2 point to the same thing (whether array, list or anything else).

arr[...]=arr2 also works when copying all the data

Play about with these actions in an interactive session. Try variations in the shape of arr2 to see how values get broadcasted. Also check id(arr) to see the object that the variable points to. And arr.__array_interface__ to see the data buffer of the array. That helps you distinguish views from copies.

like image 81
hpaulj Avatar answered Sep 23 '22 02:09

hpaulj


arr_1[:] = ... changes the elements of the existing list object that arr_1 refers to.

arr_1 = ... makes the name arr_1 refer to a different list object.

The main difference is what happens if some other name also referred to the original list object. If that's the case, then the former updates the thing that both names refer to; while the latter changes what one name refers to while leaving the other referring to the original thing.

>>> a = [0]
>>> b = a
>>> a[:] = [1]
>>> print(b)
[1]                 <--- note, change reflected by a and b
>>> a = [2]
>>> print(b)
[1]                 <--- but now a points at something else, so no change to b
like image 34
Amber Avatar answered Sep 27 '22 02:09

Amber