-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.

1

2 Answers 2

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]])
Sign up to request clarification or add additional context in comments.

Comments

0

You could also do this.

cond = a==-99999 # define condition
a[cond] = b[cond] # update a with target values of b

2 Comments

@ CypherX this is accepted way too but np.copyto seems to be the fastest way. This is a duplicate btw.
@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.

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.