Home > Net >  How can I change element of numpy array manually?
How can I change element of numpy array manually?

Time:11-12

Following is my numpy array.

import numpy as np

arr = np.array([1,2,3,4,5])
arrc=arr
arrc[arr<3]=3

When I run

>>> arrc
output : array([3,3,3,4,5])

>>> arr
output : array([3,3,3,4,5])

I expected changing arrc does not affect arr. However, both array is changing. In my actual code I am changing arrc multiple times so I observe error if arrc have influence to arr. Is there any good way to fix this?

CodePudding user response:

Simply, just index the element and set the value.

a[1,2] = "some value"

CodePudding user response:

You have to .copy() when you copy array values. Otherwise, it is the same reference you update with both variables.

Use:

arrc = arr.copy()
  • Related