我有两个(或更多)numpy数组,我需要在每个单元格上执行一次计算,其中所有匹配的单元格位置都有非空值。
import numpy
arr_a = numpy.zeros(shape=(5,6))
arr_a.fill(numpy.nan)
arr_b = numpy.zeros(shape=(5,6))
arr_b.fill(numpy.nan)
arr_a[1,1] = 12.9
arr_b[1,1] = 99.2
arr_b[1,2] = 99.2
样品:
arr_a:
array([[ nan, nan, nan, nan, nan, nan],
[ nan, 12.9, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan]])
arr_b:
array([[ nan, nan, nan, nan, nan, nan],
[ nan, 99.2, 99.2, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan],
[ nan, nan, nan, nan, nan, nan]])
因此,通过上面的示例,我希望只有1个单元(1,1)
匹配。
基本上,我想做这样的事情:
results = defaultdict(list)
mask = numpy.logical_and(arr_a, arr_b)
for arr in (a, b):
# filter out non-overlapping values
filtered_arr = arr.apply(mask)
for cell in numpy.nditer(filtered_arr[filtered_arr != numpy.nan]):
result = big_calc(filtered_arr[cell])
results[cell].append(result)
仍然不太喜欢numpy
我尝试使用numpy.logical_and(arr_a, arr_b)
,但似乎只是返回所有True
。
有干净的方法吗?
答案 0 :(得分:5)
测试Not Not-A-Number(不是NAN):
from numpy import isnan
result = ~isnan(arr_a) * ~isnan(arr_b)
或者,如果要排除NAN和无穷大,请运行:
from numpy import isfinite
isfinite(arr_a) * isfinite(arr_b)
在您的测试阵列上,以上两者都返回:
array([[False, False, False, False, False, False],
[False, True, False, False, False, False],
[False, False, False, False, False, False],
[False, False, False, False, False, False],
[False, False, False, False, False, False]], dtype=bool)
仅在(1,1)位置为真。