我有一个 NumPy 整数数组,想用 nans 替换一些值。这需要将类型转换为浮点数,如果我这样做很天真:
import numpy as np
x = 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但我不知道发生了什么。
编辑:如果没有重新定义,我怎么能写呢,即。在一条线上?
慕标琳琳
相关分类