【问题标题】:Python 2D array replace value by NaN when other array is NaN当其他数组为 NaN 时,Python 2D 数组将值替换为 NaN
【发布时间】:2021-12-08 11:46:16
【问题描述】:

我有 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),所以我不想手动操作。

【问题讨论】:

    标签: python arrays nan mask


    【解决方案1】:

    您可以使用A.shape 创建np.zeros,然后使用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.]])
    

    【讨论】:

    • 你真的不需要第二次重新创建 B
    • @MadPhysicist 好的,明白 ;)
    【解决方案2】:

    您可以直接使用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)
    

    【讨论】:

    • @user1740577。您的答案很好,但是您将两种本身更简单的方法混为一谈。感谢您的认可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    相关资源
    最近更新 更多