当前位置: 代码迷 >> python >> 如何从 numpy 矩阵中删除 nan 和 inf 值?
  详细解决方案

如何从 numpy 矩阵中删除 nan 和 inf 值?

热度:100   发布时间:2023-07-14 09:52:37.0

这是我的代码

import numpy as np
cv = [[1,3,4,56,0,345],[2,3,2,56,87,255],[234,45,35,76,12,87]]
cv2 = [[1,6,4,56,0,345],[2,3,4,56,187,255],[234,45,35,0,12,87]]

output = np.true_divide(cv,cv2,where=(cv!=0) | (cv2!=0))
print(output)`

我得到了 Nan 和 inf 值。一旦我删除了 Nan 然后我删除了 Inf 值并将它们替换为 0,我尝试以不同的方式删除它们。但是我需要将它们替换在一起!有什么方法可以将它们替换在一起?

您可以使用以下掩码替换NaN和无限值:

output[~np.isfinite(output)] = 0

>>> output
array([[1.        , 0.5       , 1.        , 1.        , 0.        ,
        1.        ],
       [1.        , 1.        , 0.5       , 1.        , 0.46524064,
        1.        ],
       [1.        , 1.        , 1.        , 0.        , 1.        ,
        1.        ]])

如果您不想就地修改数组,可以使用np.ma库,并创建一个掩码数组:

np.ma.masked_array(output, ~np.isfinite(output)).filled(0)

array([[1.        , 0.5       , 1.        , 1.        , 0.        ,
        1.        ],
       [1.        , 1.        , 0.5       , 1.        , 0.46524064,
        1.        ],
       [1.        , 1.        , 1.        , 0.        , 1.        ,
        1.        ]])

有一个特殊的功能:

numpy.nan_to_num(x_arr, copy=False, nan=0.0, posinf=0.0, neginf=0.0)