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

你可能感兴趣的:(Python3,python)