Kyle
Kyle

Reputation: 90

How can I change element of numpy array manually?

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?

Upvotes: 0

Views: 152

Answers (2)

Austin
Austin

Reputation: 26039

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

Use:

arrc = arr.copy()

Upvotes: 1

Royadma
Royadma

Reputation: 11

Simply, just index the element and set the value.

a[1,2] = "some value"

Upvotes: 1

Related Questions