Reputation: 1423
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?
Upvotes: 0
Views: 59
Reputation: 880777
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]]
Upvotes: 1