我有一个 NumPy 整数数组,想用 nans 替换一些值。这需要将类型转换为浮点数,如果我这样做很天真:import numpy as npx = np.arange(5)# 1)x = x.astype(float)[x==2]=np.nan# 2) this does not change the values inside x# x.astype(float)[x==2]=np.nan我有AttributeError: 'float' object has no attribute 'astype'在1) 的情况下,在2)中没有变化。如果我之前重新定义类型,一切正常x:x = np.arange(5)x = x.astype(float)x[x==2]=np.nan# array([ 0., 1., nan, 3., 4.])这里发生了什么?我认为错误消息指的是,np.nan但我不知道发生了什么。编辑:如果没有重新定义,我怎么能写呢,即。在一条线上?
1 回答

慕标琳琳
TA贡献1830条经验 获得超9个赞
我总结了来自@Swier、@MrFuppes 和@hpaulj 的评论的所有回复,这些回复回答了这个问题。
x.astype(float)
生成一个新数组,而不是视图——它x
以浮点数形式返回,然后可以将其分配给其他对象(在我的示例中,我用 覆盖了现有的x
)x = x.astype(float)
。
另一方面,x[x==2] = np.nan
将 nans 分配给现有数组的某些值,它不会返回任何内容。修改它不会修改原来的数组x
。
要在一行中做我想做的事,可以使用np.where
:
x = np.where(x==2, np.nan, x.astype(float))
添加回答
举报
0/150
提交
取消