0

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?

June Skeeter
  • 1,142
  • 2
  • 13
  • 27

1 Answers1

2

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.

Randy
  • 14,349
  • 2
  • 36
  • 42