Python 当其他数组为 NaN 时,二维数组用 NaN 替换值
Python 2D array replace value by NaN when other array is NaN
我有 2 个数组:
import numpy as np
A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
B = np.zeros((len(A),len(A[0])))
对于 A 中的每个 NaN,我想用 np.nan 替换 B 中相应索引处的零。我怎样才能做到这一点 ?我试过戴口罩,但没用。
B = np.ma.masked_where(np.isnan(A) == True, np.nan)
实际上我正在使用更大的阵列 (582x533),所以我不想手动完成。
您可以像下面这样创建 np.zeros
with A.shape
then use np.where
:
(这种方法构造B两次)
>>> import numpy as np
>>> A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
>>> B = np.zeros(A.shape)
>>> B = np.where(np.isnan(A) , np.nan, B)
>>> B
array([[nan, nan, 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
可以直接使用np.isnan(A)
:
B = np.zeros_like(A)
B[np.isnan(A)] = np.nan
np.where
当你想直接构造 B
时很有用:
B = np.where(np.isnan(A), np.nan, 0)
我有 2 个数组:
import numpy as np
A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
B = np.zeros((len(A),len(A[0])))
对于 A 中的每个 NaN,我想用 np.nan 替换 B 中相应索引处的零。我怎样才能做到这一点 ?我试过戴口罩,但没用。
B = np.ma.masked_where(np.isnan(A) == True, np.nan)
实际上我正在使用更大的阵列 (582x533),所以我不想手动完成。
您可以像下面这样创建 np.zeros
with A.shape
then use np.where
:
(这种方法构造B两次)
>>> import numpy as np
>>> A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
>>> B = np.zeros(A.shape)
>>> B = np.where(np.isnan(A) , np.nan, B)
>>> B
array([[nan, nan, 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
可以直接使用np.isnan(A)
:
B = np.zeros_like(A)
B[np.isnan(A)] = np.nan
np.where
当你想直接构造 B
时很有用:
B = np.where(np.isnan(A), np.nan, 0)