猿问

当 numpy dtype 为“object”时将 nan 转换为零

我有一个包含 nan 的 numpy 数组。我尝试使用将这些 nan 转换为零

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

但它没有用。我怀疑它是因为 X_ 的 dtype 是对象。我尝试使用将其转换为 float64

X_= X_.astype(np.float64)

但这也不起作用

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


慕田峪4524236
浏览 313回答 3
3回答

小怪兽爱吃肉

如果您的数组仅包含“合理”(见下文)元素,那么您可以使用以下解决方法:np.where(X_==X_,X_,0)合理的意思是元素 e 满足 e==e 唯一的例外是 nan。例如,如果没有用户定义的类用作元素,则应该是这种情况。

翻翻过去那场雪

似乎由于对象类型,转换为浮点数不起作用。可能有点hacky,但您可以尝试转换为str:X_.astype(str).replace('np.NaN', 0).astype(float)

侃侃无极

“对象” 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), '\n\n')输出:Creating a numpy array from a mixed type DataFrame can create an 'object' numpy array dtype:A: [ 1.  2.  3. nan] float64B: [[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.]
随时随地看视频慕课网APP

相关分类

Python
我要回答