将numpy导入为np
我有一个给定的数组(a):
a = np.array([[99,2,3,4,99],
[6,7,8,99,10]])
我有3个参考数组(b,c和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]])
参考数组以这种形式一起给出:
references = np.array([b,c,d])
我必须使用最近的索引替换给定数组'a'中的值'99' 如果“非99”值可用,则参考数组的值。
预期的答案是:
answer = np.array([[21,2,3,4,35],
[6,7,8,99,10]])
最快的做法是什么?
答案 0 :(得分:1)
您可以使用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))
产量
[[21 2 3 4 35]
[ 6 7 8 99 10]]