Wesley Skeeter Wesley Skeeter - 1 month ago 9
Python Question

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?

Answer

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.

Comments