添加两个2D NumPy数组,忽略其中的NaN

时间:2015-10-21 21:14:45

标签: python arrays numpy nan

使用numpy.nan作为缺失值添加2个numpy数组a和b(均为2D)的正确方法是什么?

  1. a + b
    1. numpy.ma.sum(a,b)

2 个答案:

答案 0 :(得分:8)

由于输入是2D数组,您可以使用np.dstack沿第三轴堆叠它们,然后使用np.nansum来确保忽略NaNs,除非NaNs在两个输入数组中,输出也有NaN。因此,实现看起来像这样 -

np.nansum(np.dstack((A,B)),2)

示例运行 -

In [157]: A
Out[157]: 
array([[ 0.77552455,  0.89241629,         nan,  0.61187474],
       [ 0.62777982,  0.80245533,         nan,  0.66320306],
       [ 0.41578442,  0.26144272,  0.90260667,         nan],
       [ 0.65122428,  0.3211213 ,  0.81634856,         nan],
       [ 0.52957704,  0.73460363,  0.16484994,  0.20701344]])

In [158]: B
Out[158]: 
array([[ 0.55809925,  0.1339353 ,         nan,  0.35154039],
       [ 0.94484722,  0.23814073,  0.36048809,  0.20412318],
       [ 0.25191484,         nan,  0.43721322,  0.95810905],
       [ 0.69115038,  0.51490958,         nan,  0.44613473],
       [ 0.01709308,  0.81771896,  0.3229837 ,  0.64013882]])

In [159]: np.nansum(np.dstack((A,B)),2)
Out[159]: 
array([[ 1.3336238 ,  1.02635159,         nan,  0.96341512],
       [ 1.57262704,  1.04059606,  0.36048809,  0.86732624],
       [ 0.66769925,  0.26144272,  1.33981989,  0.95810905],
       [ 1.34237466,  0.83603089,  0.81634856,  0.44613473],
       [ 0.54667013,  1.55232259,  0.48783363,  0.84715226]])

答案 1 :(得分:4)

只需在两个数组中用零替换NaN

a[np.isnan(a)] = 0  # replace all nan in a with 0
b[np.isnan(b)] = 0  # replace all nan in b with 0

然后执行添加:

a + b

这取决于0"identity element"添加的事实。