如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
当前回答
做到以上几点:
x = x[~numpy.isnan(x)]
or
x = x[numpy.logical_not(numpy.isnan(x))]
我发现重置到相同的变量(x)并没有删除实际的nan值,必须使用不同的变量。将其设置为不同的变量删除了nan。 如。
y = x[~numpy.isnan(x)]
其他回答
试试这个:
import math
print [value for value in x if not math.isnan(value)]
要了解更多,请阅读列表推导式。
简单地填充
x = numpy.array([
[0.99929941, 0.84724713, -0.1500044],
[-0.79709026, numpy.NaN, -0.4406645],
[-0.3599013, -0.63565744, -0.70251352]])
x[numpy.isnan(x)] = .555
print(x)
# [[ 0.99929941 0.84724713 -0.1500044 ]
# [-0.79709026 0.555 -0.4406645 ]
# [-0.3599013 -0.63565744 -0.70251352]]
使用实例删除NumPy数组x中的NaN值。
x = x[~numpy.isnan(x)]
解释
内部函数numpy。isnan返回一个布尔/逻辑数组,当x不是数字时,该数组的值为True。因为我们想要相反的结果,所以我们使用非逻辑操作符~来获得一个数组,在x为有效数字的任何地方都是true。
最后,我们使用这个逻辑数组对原始数组x进行索引,以便只检索非nan值。
@jmetz的答案可能是大多数人需要的;然而,它会产生一个一维数组,例如,使其无法用于删除矩阵中的整行或整列。
为此,应该将逻辑数组缩减为一维,然后对目标数组进行索引。例如,下面将删除至少有一个NaN值的行:
x = x[~numpy.isnan(x).any(axis=1)]
点击这里查看更多细节。
Pandas引入了一个将所有数据类型转换为缺失值的选项。
https://pandas.pydata.org/docs/user_guide/missing_data.html
np.isnan()函数不兼容所有的数据类型,例如:
>>> import numpy as np
>>> values = [np.nan, "x", "y"]
>>> np.isnan(values)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
pd.isna()和pd.notna()函数与许多数据类型兼容,pandas引入了pd.notna()函数。NA值:
>>> import numpy as np
>>> import pandas as pd
>>> values = pd.Series([np.nan, "x", "y"])
>>> values
0 NaN
1 x
2 y
dtype: object
>>> values.loc[pd.isna(values)]
0 NaN
dtype: object
>>> values.loc[pd.isna(values)] = pd.NA
>>> values.loc[pd.isna(values)]
0 <NA>
dtype: object
>>> values
0 <NA>
1 x
2 y
dtype: object
#
# using map with lambda, or a list comprehension
#
>>> values = [np.nan, "x", "y"]
>>> list(map(lambda x: pd.NA if pd.isna(x) else x, values))
[<NA>, 'x', 'y']
>>> [pd.NA if pd.isna(x) else x for x in values]
[<NA>, 'x', 'y']