June Skeeter
June Skeeter

Reputation: 1218

Issue replacing values in numpy array

I am trying to copy an array, replace all values in the copy below a threshold but keep the original array in tact.

Here is a simplified example of what I need to do.

import numpy as np

A = np.arange(0,1,.1)
B = A
B[B<.3] = np.nan
print ('A =', A) 
print ('B =', B)

Which yields

A = [ nan  nan  nan  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
B = [ nan  nan  nan  0.3  0.4  0.5  0.6  0.7  0.8  0.9]

I can't understand why the values in A <= .3 are also overwritten?

Can someone explain this to me and suggest a work around?

Upvotes: 0

Views: 44

Answers (1)

Randy
Randy

Reputation: 14849

Change B = A to B = A.copy() and this should work as expected. As written, B and A refer to the same object in memory.

Upvotes: 2

Related Questions