首页 > 解决方案 > 替换值时numpy astype不起作用

问题描述

我有一个 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但是我不知道发生了什么。

编辑:如果没有重新定义,我怎么能写出来,即。在一条线上?

标签: pythonnumpy

解决方案


我会总结来自@Swier、@MrFuppes 和@hpaulj 的所有回答,这些回答回答了这个问题。

x.astype(float)生成一个新数组,而不是视图——它x以浮点数形式返回,然后可以将其分配给其他东西(在我的示例中,我用 覆盖现有xx = x.astype(float))。

另一方面,x[x==2] = np.nan将 nans 分配给现有数组的某些值,它不会返回任何内容。修改它不会修改原始数组x

要在一行中做我想做的事,可以使用np.where

x = np.where(x==2, np.nan, x.astype(float))

推荐阅读