如何从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[~numpy.isnan(x)]
的工作原理。但是如果numpy dtype不是原生数据类型(例如,如果它是object),它将抛出一个错误。在这种情况下,你可以用熊猫。
x[~pandas.isna(x)] or x[~pandas.isnull(x)]
其他回答
如果它有帮助,对于简单的1d数组:
x = np.array([np.nan, 1, 2, 3, 4])
x[~np.isnan(x)]
>>> array([1., 2., 3., 4.])
但如果你希望扩展到矩阵并保留形状:
x = np.array([
[np.nan, np.nan],
[np.nan, 0],
[1, 2],
[3, 4]
])
x[~np.isnan(x).any(axis=1)]
>>> array([[1., 2.],
[3., 4.]])
我在处理pandas .shift()功能时遇到了这个问题,我想避免使用.apply(…,轴=1)由于其效率低下,不惜一切代价。
对我来说,@jmetz的答案不工作,但是使用pandas isnull()做到了。
x = x[~pd.isnull(x)]
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']
filter(lambda v: v==v, x)
既适用于列表和numpy数组 因为v !=v仅用于NaN
简单地填充
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]]