-1

I have a numpy object array (a) that contains values of -99999 across large areas of the array.

I want to set the values in a that are == to -99999, equal the the values of a second array (b).

b is the same size as a but I can't get it to work to replace those values.

  • Does this answer your question? [replacing numpy array elements that are non zero](https://stackoverflow.com/questions/63661231/replacing-numpy-array-elements-that-are-non-zero) – mathfux Oct 07 '20 at 00:44

2 Answers2

1

You can do it with np.copyto:

np.copyto(a, b, where = a==-999999)

Sample run:

>>> a = np.random.choice([0,1,-999999], size=[5, 6], p=[0.15, 0.15, 0.7])
>>> b = np.random.choice([0,1, 2], size=[5, 6], p=[0.3, 0.4, 0.3])
>>> a
array([[-999999, -999999, -999999,       1,       1, -999999],
       [      0, -999999, -999999, -999999, -999999, -999999],
       [-999999,       1, -999999, -999999, -999999,       0],
       [      0, -999999, -999999, -999999, -999999, -999999],
       [      0,       1, -999999, -999999,       0, -999999]])
>>> b
array([[1, 1, 2, 2, 2, 0],
       [0, 0, 2, 1, 1, 0],
       [0, 1, 1, 1, 2, 1],
       [1, 1, 2, 0, 0, 0],
       [0, 2, 0, 2, 2, 2]])
>>> np.copyto(a, b, where = a==-999999)
>>> a
array([[1, 1, 2, 1, 1, 0],
       [0, 0, 2, 1, 1, 0],
       [0, 1, 1, 1, 2, 0],
       [0, 1, 2, 0, 0, 0],
       [0, 1, 0, 2, 0, 2]])
mathfux
  • 5,759
  • 1
  • 14
  • 34
0

You could also do this.

cond = a==-99999 # define condition
a[cond] = b[cond] # update a with target values of b
CypherX
  • 7,019
  • 3
  • 25
  • 37
  • @ CypherX this is accepted way too but `np.copyto` seems to be the [fastest way](https://stackoverflow.com/a/63661277/3044825). This is a duplicate btw. – mathfux Oct 07 '20 at 00:43
  • @mathfux I liked the analysis in the other post of yours! I had not used `np.copyto` earlier. So, thank you for mentioning that here. I am voting it up. But the answer is not a duplicate as what I mentioned, uses the very basics of numpy. – CypherX Oct 10 '20 at 17:09