如何从NumPy数组中删除NaN值?

[1, 2, NaN, 4, NaN, 8]   ⟶   [1, 2, 4, 8]

当前回答

使用实例删除NumPy数组x中的NaN值。

x = x[~numpy.isnan(x)]

解释

内部函数numpy。isnan返回一个布尔/逻辑数组,当x不是数字时,该数组的值为True。因为我们想要相反的结果,所以我们使用非逻辑操作符~来获得一个数组,在x为有效数字的任何地方都是true。

最后,我们使用这个逻辑数组对原始数组x进行索引,以便只检索非nan值。

其他回答

filter(lambda v: v==v, x)

既适用于列表和numpy数组 因为v !=v仅用于NaN

做到以上几点:

x = x[~numpy.isnan(x)]

or

x = x[numpy.logical_not(numpy.isnan(x))]

我发现重置到相同的变量(x)并没有删除实际的nan值,必须使用不同的变量。将其设置为不同的变量删除了nan。 如。

y = x[~numpy.isnan(x)]

最简单的方法是:

numpy.nan_to_num(x)

文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html

对我来说,@jmetz的答案不工作,但是使用pandas isnull()做到了。

x = x[~pd.isnull(x)]

如果你使用numpy

# first get the indices where the values are finite
ii = np.isfinite(x)

# second get the values
x = x[ii]