Numpy array overwritten in nested function

888 views Asked by At

The problem I have is that when I send an array (array "a" in code below) to a function ("summation" in code below), then assign it to another array (array "d" in code below), any change in elements of array "d" is reflected on array "a" as well.

from numpy import *

def summation(a,b):
    a_row = len(a[:,1])
    b_row=len(a[1,:])
    d = a
    for i in range(a_row):
        for j in range(a_col):
            d[i,j]=d[i,j]+b[i,j]
    return d

def define():
    a = array([[1,2,3,4,5],[6,7,8,9,10]])
    b = array([[11,12,13,14,15],[16,17,18,19,20]])
    z=summation(a,b)
    print a
    print b
    print z

define()

So when I run this code, the output is:

[[12 14 16 18 20]
 [22 24 26 28 30]]
[[11 12 13 14 15]
 [16 17 18 19 20]]
[[12 14 16 18 20]
 [22 24 26 28 30]]

I would like "a" to be untouched and does not change. Please help me if you have any solution.

2

There are 2 answers

1
Namit Singal On

The problem is that you are assigning reference of a to d, since a list/in this case numpy array are mutable, any changes to d, will also affect values in a.

EDIT:- @EdChum thanks for the better way Numpy has a builtin copy function, since a is already a numpy array, you could use:-

d = a.copy()

@Old way which needs an additional import:-

import copy
d = copy.deepcopy(a)

instead of doing d=a

0
Tuan Anh Hoang-Vu On

You can use built-in function of numpy: numpy.copy:

d = numpy.copy(a)