Python 3.x 在特定情况下,如何用1替换nan

Python 3.x 在特定情况下,如何用1替换nan,python-3.x,numpy,Python 3.x,Numpy,在我的程序中,我有一些数组,我使用一个简单的公式来计算一个值。我正在使用的代码 from itertools import combinations import numpy as np res = [ np.array([[12.99632095], [29.60571445], [-1.85595153], [68.78926787], [2.75185088], [2.75204384]]), np.array([[15.66458062], [0], [-3.75927

在我的程序中,我有一些数组,我使用一个简单的公式来计算一个值。我正在使用的代码

from itertools import combinations
import numpy as np

res = [
    np.array([[12.99632095], [29.60571445], [-1.85595153], [68.78926787], [2.75185088], [2.75204384]]),
    np.array([[15.66458062], [0], [-3.75927882], [0], [2.30128711], [197.45459974]]),
    np.array([[10.66458062], [0], [0], [-2.65954113], [-2.30128711], [197.45459974]]),
]


def cal():
    pairs = combinations(res, 2)
    results = []
    for pair in pairs:
        r = np.concatenate(pair, axis=1)
        r1 = r[:, 0]
        r2 = r[:, 1]
        sign = np.sign(r1 * r2)
        result = np.multiply(sign, np.min(np.abs(r), axis=1) / np.max(np.abs(r), axis=1))

        results.append(result)
    return results
我得到的结果是

RuntimeWarning: invalid value encountered in true_divide
  result = np.multiply(sign, np.min(np.abs(r), axis=1) / np.max(np.abs(r), axis=1))
[array([0.82966287, 0.        , 0.49369882, 0.        , 0.83626883,
       0.0139376 ]), array([ 0.82058458,  0.        ,  0.        , -0.03866215, -0.83626883,
        0.0139376 ]), array([ 0.68080856,         nan,  0.        ,  0.        , -1.        ,
        1.        ])]
在这里,我得到第三个输出数组的
nan
。我明白,我得到了
nan
是因为
0/0

因为数组的大小或
0
的位置不是固定的。因此,我想以这种方式更改代码,如果我得到
0/0
,在这里,而不是
nan
,我想保存
1


您能告诉我如何处理此问题吗?

可能的解决方案之一:

import itertools as it

def cal():
    pairs = it.combinations(res, 2)
    rv = []
    for pair in pairs:
        r = np.concatenate(pair, axis=1)
        sign = np.sign(np.prod(r, axis=1))
        t1 = np.min(np.abs(r), axis=1)
        t2 = np.max(np.abs(r), axis=1)
        ratio = np.full(shape=r.shape[0], fill_value=1.)
        np.divide(t1, t2, out=ratio, where=np.not_equal(t2, 0.))
        wrk = np.full(shape=r.shape[0], fill_value=1.)
        np.multiply(sign, ratio, out=wrk, where=np.not_equal(t2, 0.))
        rv.append(wrk)
    return rv
我使用了
np.sign(np.prod(r,axis=1))而不是
np.sign(r1*r2)

然后设置默认值而不是NaN的诀窍是我创建了 填充此默认值的数组,称为
np.divide
passing 只在除数不为0的情况下才进行除法

最后一步是np.multiply,使用相同的where条件

要测试此代码并打印结果,可以运行:

with np.printoptions(formatter={'float': '{: 9.5f}'.format}):
    result = cal()
    for tbl in result:
        print(tbl)
结果是:

[  0.82966   0.00000   0.49370   0.00000   0.83627   0.01394]
[  0.82058   0.00000   0.00000  -0.03866  -0.83627   0.01394]
[  0.68081   1.00000   0.00000   0.00000  -1.00000   1.00000]
如您所见,在最后一种情况下,共有2个1.0值
第二个和第三个源数组中的值相同。

numpy有一个专门为此用例设计的函数:
np.nan\u to\u num()
@obchardon谢谢。您的意思是,在获得
nan
后更改输出数组吗?实际上,我想保存的
1
是我得到的
0/0
非常感谢。只要给我一些时间,在申请我的代码后,我会让你知道的。