多次 Numpy 掩码数组,并用另一个 3D 数组的值填充 3D 数组中的 nans

Numpy mask array multiple times and fill nans in 3D array with values from another 3D array

我有以下代码:

import numpy as np



def fill(arr1, arr2, arr3, arr4, thresh= 0.5):
    out_arr = np.zeros(arr1.shape)
    for i in range(0,len(arr1)):
        arr1[i] = np.where(np.abs(arr1[i])<=thresh,np.nan,arr1[i])
        mask = np.isnan(arr1[i])
        arr1[i] = np.nan_to_num(arr1[i])
        merged1 = (arr2[i]*mask)+arr1[i]


        merged2 = np.where(np.abs(merged1)<=thresh,np.nan,merged1)
        mask = np.isnan(merged2)
        merged2 = np.nan_to_num(merged2)
        merged3 = (arr3[i]*mask)+merged2

        merged3 = np.where(np.abs(merged3)<=thresh,np.nan,merged3)
        mask = np.isnan(merged3)
        merged3 = np.nan_to_num(merged3)
        merged4 = (arr4[i]*mask)+merged3



        out_arr[i] = merged4


    return(out_arr)




arr1 = np.random.rand(10, 10, 10)
arr2 = np.random.rand(10, 10, 10)
arr3 = np.random.rand(10, 10, 10)
arr4 = np.random.rand(10, 10, 10)
arr = fill(arr1, arr2, arr3, arr4, 0.5)

我想知道是否有更有效的方法来使用掩码数组?基本上我正在做的是用下一个数组替换 3D 数组每一层中低于阈值的值,这超过 4 个数组。对于 n 个数组,这看起来如何? 谢谢!

您的函数可以通过多种方式进行简化。在效率上,最显着的一点是不需要遍历第一个维度,直接对整个数组进行操作。除此之外,您可以将替换逻辑重构为更简单的东西,并使用循环来避免一遍又一遍地重复相同的代码:

import numpy as np

# Function accepts as many arrays as wanted, with at least one
# (threshold needs to be passed as keyword parameter)
def fill(arr1, *arrs, thresh=0.5):
    # Output array
    out_arr = arr1.copy()
    for arr in arrs:
        # Replace values that are still below threshold
        mask = np.abs(out_arr) <= thresh
        out_arr[mask] = arr[mask]
    return out_arr

由于thresh需要在这个函数中作为关键字参数传递,你可以这样称呼它:

arr = fill(arr1, arr2, arr3, arr4, thresh=0.5)