Python中如何快速将nan值转换成0

今天遇到”如何将数组中的nan转换成0“的问题,查阅资料后已解决,保留笔记供以后学习。

import numpy as np

a = np.array([np.nan, np.nan, 0, 1])

print(a)

结果为

array([nan, nan,  0.,  1.])

通过调用numpy.nan_to_num函数,可快速将nan转换成0值

np.nan_to_num(a)

结果为

array([0., 0., 0., 1.])

numpy.nan_to_num函数源码如下,nan_to_num函数不仅可以把nan替换成规定值,还可以处理np.inf的情况,可通过nan、posinf、neginf设置转换值

def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None):
    """
    Replace NaN with zero and infinity with large finite numbers (default
    behaviour) or with the numbers defined by the user using the `nan`, 
    `posinf` and/or `neginf` keywords.

    If `x` is inexact, NaN is replaced by zero or by the user defined value in
    `nan` keyword, infinity is replaced by the largest finite floating point 
    values representable by ``x.dtype`` or by the user defined value in 
    `posinf` keyword and -infinity is replaced by the most negative finite 
    floating point values representable by ``x.dtype`` or by the user defined 
    value in `neginf` keyword.

    For complex dtypes, the above is applied to each of the real and
    imaginary components of `x` separately.
    ...
    """

参考文献:

https://blog.csdn.net/u010158659/article/details/50814706/

https://www.cnblogs.com/smuxiaolei/p/7390045.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值