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
令数组全部的值为0value in `neginf` keyword.
For complex dtypes, the above is applied to each of the real and
imaginary components of `x` separately.
...
"""
参考⽂献:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。