为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪4524236 2022-05-24 15:03:55
我有一个包含 nan 的 numpy 数组。我尝试使用将这些 nan 转换为零 X_ = np.nan_to_num(X_, copy = False)但它没有用。我怀疑它是因为 X_ 的 dtype 是对象。我尝试使用将其转换为 float64X_= X_.astype(np.float64)但这也不起作用当 dtype 是对象时,有没有办法将 nan 转换为零?
查看完整描述

3 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

如果您的数组仅包含“合理”(见下文)元素,那么您可以使用以下解决方法:

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

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


查看完整回答
反对 回复 2022-05-24
?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

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

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


查看完整回答
反对 回复 2022-05-24
?
侃侃无极

TA贡献2051条经验 获得超10个赞

“对象” 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] 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.]


查看完整回答
反对 回复 2022-05-24
  • 3 回答
  • 0 关注
  • 311 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号