python - 替换值时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
但是我不知道发生了什么。
编辑:如果没有重新定义,我怎么能写出来,即。在一条线上?
解决方案
我会总结来自@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))
推荐阅读
- javascript - 使用 Javascript 复制到剪贴板功能
- ios - 以编程方式将 UIbutton 添加到表格视图内的单元格。滚动后与其他单元格聚集在一起的数据
- c++ - boost::format() 似乎不是线程安全的,因为 std::ctype
::narrow() 不是线程安全的 - javascript - 如何在 Rails 中制作无限滚动?
- domain-driven-design - 在微服务中,是否可以接受 API 返回已复制的聚合根?
- c++ - unique_ptr 多态性内存泄漏
- https - dotnet core 2.1.302 Ubuntu Linux 开发证书信任
- linux - stat 缺少操作数错误
- angular - 如何在 Angular Dart 中使用带有 ngModel 的自定义数据类型
- javascript - 如何停止滚动上一页?