0

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?

2
  • You might mean arrc = arr.copy(). Otherwise arrc and arr are references to the same array. Commented Nov 12, 2022 at 3:59
  • arrc=arr - just assigns the same object to the new variable name. It does not make a copy. This isn't just a numpy thing; it's basic Python. But with numpy you also have to know when something is a view instead of a copy. Commented Nov 12, 2022 at 16:31

2 Answers 2

1

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

Use:

arrc = arr.copy()
Sign up to request clarification or add additional context in comments.

Comments

1

Simply, just index the element and set the value.

a[1,2] = "some value"

1 Comment

I have to use conditions because in my actual code the array has more than 20,000 index and they are in random order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.