我有两个3D矩阵(A和B),两者都包含随机元素中的NaN。我正在比较这两个矩阵,并且在其中至少有一个含有NaN的地方,我希望它们都含有NaN。换句话说,如果它们都没有在该索引处包含NaN,我想用NaN替换该索引值。使用python函数有效的方法吗?
import numpy as np
# Create the fake variables A and B. Here is what A and B look like initially:
A = np.array([[1, 2, np.nan], [4, np.nan, 6], [np.nan, 8, 9]])
B = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 8, 9]])
# What I want A and B to look like in the end:
A
array([[ 1., 2., nan],
[ 4., nan, nan],
[ nan, 8., 9.]])
B
array([[ 1., 2., nan],
[ 4., nan, nan],
[ nan, 8., 9.]])
答案 0 :(得分:2)
您需要numpy.isnan()
和boolean indexing。
>>> A[np.isnan(B)] = np.nan
>>> B[np.isnan(A)] = np.nan