在 numpy 矩阵中将 "nan" 值转换为不同于 0 的不同值

Converting "nan" values to a different value different than 0 in a numpy matrix

我有这样一个 numpy 矩阵:

[[182 93 107 ..., nan nan -1]
 [182 93 107 ..., nan nan -1]
 [182 93 110 ..., nan nan -1]
 ..., 
 [188 95 112 ..., nan nan -1]
 [188 97 115 ..., nan nan -1]
 [188 95 112 ..., nan nan -1]]

我想将 nan 值更改为非零值。为此,我使用了这个技巧:

x_train[np.isnan(x_train)] = -10

但是我得到了这个错误:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''.

我该如何解决这个问题?

谢谢,

你可以使用numpy的copyto函数:

import numpy as np

xtrain = np.array([[0.3, np.nan],[1.0, np.nan]])
default = np.empty([2,2])
default.fill(-10)
print(xtrain)
np.copyto(xtrain,default,'no',np.isnan(xtrain))
print(xtrain)

如果您的初始数组是可以有意义地解释为 float 的字符串,那么您可以使用 astype:

进行转换
b = np.array([['182', '93', '107', 'nan', 'nan', '-1'],
 ['182', '93', '107', 'nan', 'nan', '-1'],
 ['182', '93', '110', 'nan', 'nan', '-1'],
 ['188', '95', '112', 'nan', 'nan', '-1'],
 ['188', '97', '115', 'nan', 'nan', '-1'],
 ['188', '95', '112', 'nan', 'nan', '-1']])

c = b.astype(np.float)
c[np.isnan(c)]=-10

array([[ 182.,   93.,  107.,  -10.,  -10.,   -1.],
       [ 182.,   93.,  107.,  -10.,  -10.,   -1.],
       [ 182.,   93.,  110.,  -10.,  -10.,   -1.],
       [ 188.,   95.,  112.,  -10.,  -10.,   -1.],
       [ 188.,   97.,  115.,  -10.,  -10.,   -1.],
       [ 188.,   95.,  112.,  -10.,  -10.,   -1.]])

您可以尝试使用数组迭代器,例如:

import numpy as np


a = np.empty((6,4))
a.fill(0.25)
a[2].fill(np.nan)      
for x in np.nditer(a, op_flags=['readwrite']):
    if np.isnan(x):
        x[...]=-10