如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
如何从NumPy数组中删除NaN值?
[1, 2, NaN, 4, NaN, 8] ⟶ [1, 2, 4, 8]
当前回答
最简单的方法是:
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.nan_to_num(x)
文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html
简单地填充
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]]
接受的答案改变了2d数组的形状。 我在这里提供了一个解决方案,使用Pandas dropna()功能。 它适用于1D和2D数组。在2D情况下,可以选择weather删除包含np.nan的行或列。
import pandas as pd
import numpy as np
def dropna(arr, *args, **kwarg):
assert isinstance(arr, np.ndarray)
dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
if arr.ndim==1:
dropped=dropped.flatten()
return dropped
x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )
print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')
print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')
print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')
结果:
==================== 1D Case: ====================
Input:
[1400. 1500. 1600. nan nan nan 1700.]
dropna:
[1400. 1500. 1600. 1700.]
==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna (rows):
[[1400. 1500. 1600.]]
dropna (columns):
[[1500.]
[ 0.]
[1800.]]
==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna:
[1400. 1500. 1600. 1700.]
如果你使用numpy
# first get the indices where the values are finite
ii = np.isfinite(x)
# second get the values
x = x[ii]