gpt4 book ai didi

当其他数组为 NaN 时,Python 2D 数组将值替换为 NaN

转载 作者:行者123 更新时间:2023-12-02 18:29:12 25 4
gpt4 key购买 nike

我有 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.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)

关于当其他数组为 NaN 时,Python 2D 数组将值替换为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69666582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com