0

import numpy as np

I have a given array (a):

a = np.array([[99,2,3,4,99],
              [6,7,8,99,10]])

I have 3 reference arrays (b,c,and d):

b = np.array([[99,12,13,14,99],
              [16,17,99,99,20]])

c = np.array([[21,22,23,24,99],
              [26,27,99,99,30]])

d = np.array([[31,32,33,34,35],
              [36,37,99,99,40]])

The reference arrays are given together in this form:

references = np.array([b,c,d])

I have to replace the value '99' in a given array 'a' using the nearest index value from the reference arrays if 'non 99' value is available.

The expected answer is:

answer = np.array([[21,2,3,4,35],
              [6,7,8,99,10]])

What is the fastest way of doing it?

0

1 Answer 1

1

You could use np.select:

import numpy as np

a = np.array([[99,2,3,4,99],
              [6,7,8,99,10]])

b = np.array([[99,12,13,14,99],
              [16,17,99,99,20]])

c = np.array([[21,22,23,24,99],
              [26,27,99,99,30]])

d = np.array([[31,32,33,34,35],
              [36,37,99,99,40]])

references = np.array([b,c,d])

choices = np.concatenate([a[None, ...], references])
conditions = (choices != 99)

print(np.select(conditions, choices, default=99))

yields

[[21  2  3  4 35]
 [ 6  7  8 99 10]]
Sign up to request clarification or add additional context in comments.

Comments

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.