gpt4 book ai didi

python - numpy 按类型元素搜索并更改它

转载 作者:行者123 更新时间:2023-12-01 09:16:21 25 4
gpt4 key购买 nike

我有一个二维数组a和二维数组b。我需要计算c =a/b,所以有一些 infNaN 对象。如何使用 numpy 检查它并将它们设置为 np.nan

这是我的代码:

import numpy as np
a=np.asarray([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])
b=np.asarray([[1,2,0,4,5],[1,2,0,4,5],[1,2,0,4,5],[1,2,3,4,5]])
c=a/b
b=np.where(isinstance(c, float),np.nan,c)

最佳答案

我不确定,如果我错了,请纠正我,您正在引用 c 中的 inf 对象,即在计算 c = a/b 之后。

示例代码如下:

import numpy as np
np.seterr(divide='ignore', invalid='ignore') #To avoid RuntimeWarning: divide by zero encountered in true_divide after removing the cwd from sys.path.
a=np.asarray([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])
b=np.asarray([[1,2,0,4,5],[1,2,0,4,5],[1,2,0,4,5],[1,2,3,4,5]])
c=a/b
print(c)

[[ 1. 1. inf 1. 1.]
[ 1. 1. inf 1. 1.]
[ 1. 1. inf 1. 1.]
[ 1. 1. 1. 1. 1.]]

c[np.isinf(c)] = np.nan #Finds inf object and replace with nan.
print(c)

[[ 1. 1. nan 1. 1.]
[ 1. 1. nan 1. 1.]
[ 1. 1. nan 1. 1.]
[ 1. 1. 1. 1. 1.]]

希望对你有帮助!

附上jupyter笔记本截图供引用:

enter image description here

关于python - numpy 按类型元素搜索并更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223268/

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