当 numpy dtype "object"时将 nan 转换为零



我有一个包含nan的numpy数组。我试图使用

X_ = np.nan_to_num(X_, copy = False)

但它没有用。我怀疑这是因为X_的dtype是对象。我试图使用

X_= X_.astype(np.float64)

但这也没有用

当 dtype 是对象时,有没有办法将 nan 转换为零?

a  = [np.nan]
b = np.array(a)
c = np.nan_to_num(b)
print(b)
print(c)

结果:

[nan]
[0.]

它有效。检查您的X_格式。

似乎由于对象类型的原因,转换为浮点数不起作用。可能有点笨拙,但您可以尝试转换为 str:

X_.astype(str).replace('np.NaN', 0).astype(float)

如果您的数组仅包含"合理"(见下文(元素,则可以使用以下解决方法:

np.where(X_==X_,X_,0)

合理我的意思是元素 e 满足 e==e,唯一的例外是 nan。例如,如果没有用户定义的类用作元素,则应该如此。

"object" dtype 也给我带来了一个问题。但你的astype(np.float64)确实对我有用。谢谢!

print("Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:")
A = np.array([1., 2., 3., np.nan]); print('A:', A, A.dtype)
B = pd.DataFrame([[1., 2., 3., np.nan,],  [1, 2, 3, '4']]
).to_numpy();  print('B:', B, B.dtype, 'n')
print('Converting vanilla A is fine:n', np.nan_to_num(A, nan=-99), 'n')
print('But not B:n', np.nan_to_num(B, nan=-99), 'n')
print('Not even this slice of B, nB[0, :] : ', B[0, :])
print(np.nan_to_num(B[0, :], nan=-99), 'n')
print('The astype(np.float64) does the trick here:n', 
np.nan_to_num(B[0, :].astype(np.float64), nan=-99), 'nn')

输出:

Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:
A: [ 1.  2.  3. nan] float64
B: [[1.0 2.0 3.0 nan]
[1.0 2.0 3.0 '4']] object 
Converting vanilla A is fine:
[  1.   2.   3. -99.] 
But not B:
[[1.0 2.0 3.0 nan]
[1.0 2.0 3.0 '4']] 
Not even this slice of B, 
B[0, :] :  [1.0 2.0 3.0 nan]
[1.0 2.0 3.0 nan] 
The astype(np.float64) does the trick here:
[  1.   2.   3. -99.]

最新更新