用同一位置的另一个矩阵的NA替换一个矩阵中的值

时间:2019-05-09 17:24:24

标签: python numpy

我有两个形状相同的矩阵,都填充有浮点数,但是其中一个矩阵在某些位置具有NA。我要这样做,以便其他矩阵在相同位置也有NA。

我可以想到一些幼稚的解决方案:

1)任何类型的条件循环-非常慢

2)将NA转换为0,对元素进行矩阵乘积,以使没有NA的矩阵在所需位置获得0,然后将它们按元素划分以恢复为原始值,最后将0转换为NA-速度更快,但仍然效率低下且笨拙

我想找到一种解决此问题的有效方法,因为我需要执行数百万次此操作。

1 个答案:

答案 0 :(得分:0)

如果A是具有NaN值的矩阵,而B是另一个矩阵。

import numpy as np

# Construct example matrices
A = np.random.random((3,3))
B = np.random.random((3,3))
# Set two values to np.nan
A[0,:2] = np.nan
# Set values in B to np.nan in the same locations that they occur in A
B[np.isnan(A)] = np.nan
相关问题