python - Slicing a NumPy array within a loop -


this question has answer here:

i need explanation (reference) explain numpy slicing within (for) loops. have 3 cases.

def example1(array):     row in array:         row = row + 1     return array  def example2(array):     row in array:         row += 1     return array  def example3(array):     row in array:         row[:] = row + 1     return array 

a simple case:

ex1 = np.arange(9).reshape(3, 3) ex2 = ex1.copy() ex3 = ex1.copy() 

returns:

>>> example1(ex1) array([[0, 1, 2],        [3, 4, 5],        [6, 7, 8]])  >>> example2(ex2) array([[1, 2, 3],        [4, 5, 6],        [7, 8, 9]])  >>> example3(ex3) array([[1, 2, 3],        [4, 5, 6],        [7, 8, 9]]) 

it can seen first result differs second , third.

first example:

you extract row , add 1 it. redefine pointer row not array contains! not affect original array.

second example:

you make in-place operation - affect original array - long array.

if doing double loop wouldn't work anymore:

def example4(array):     row in array:         column in row:             column += 1     return array  example4(np.arange(9).reshape(3,3)) array([[0, 1, 2],        [3, 4, 5],        [6, 7, 8]]) 

this doesn't work because don't call np.ndarray's __iadd__ (to modify data array points to) python int's __iadd__. example works because rows numpy arrays.

third example:

row[:] = row + 1 interpreted row[0] = row[0]+1, row[1] = row[1]+1, ... again works in place affects original array.

bottom line

if operating on mutable objects, lists or np.ndarray need careful change. such object points actual data stored in memory - changing pointer (example1) doesn't affect saved data. need follow pointer (either directly [:] (example3) or indirectly array.__iadd__ (example2)) change saved data.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -