如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
当前回答
如果它有帮助,对于简单的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)由于其效率低下,不惜一切代价。
其他回答
最简单的方法是:
numpy.nan_to_num(x)
文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html
试试这个:
import math
print [value for value in x if not math.isnan(value)]
要了解更多,请阅读列表推导式。
如果你使用numpy
# first get the indices where the values are finite
ii = np.isfinite(x)
# second get the values
x = x[ii]
正如其他人所示
x[~numpy.isnan(x)]
的工作原理。但是如果numpy dtype不是原生数据类型(例如,如果它是object),它将抛出一个错误。在这种情况下,你可以用熊猫。
x[~pandas.isna(x)] or x[~pandas.isnull(x)]
做到以上几点:
x = x[~numpy.isnan(x)]
or
x = x[numpy.logical_not(numpy.isnan(x))]
我发现重置到相同的变量(x)并没有删除实际的nan值,必须使用不同的变量。将其设置为不同的变量删除了nan。 如。
y = x[~numpy.isnan(x)]