且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除numpy.ndarray中包含非数字值的所有行

更新时间:2023-02-05 09:55:00

>>> a = np.array([[1,2,3], [4,5,np.nan], [7,8,9]])
array([[  1.,   2.,   3.],
       [  4.,   5.,  nan],
       [  7.,   8.,   9.]])

>>> a[~np.isnan(a).any(axis=1)]
array([[ 1.,  2.,  3.],
       [ 7.,  8.,  9.]])

,然后将其重新分配给a.

and reassign this to a.

说明:np.isnan(a)返回与True类似的数组,其中NaNFalse在其他位置. .any(axis=1)通过对整个行进行逻辑or操作将m*n数组减少为n~反转True/False,并且a[ ]仅从原始数组中选择具有True的行在方括号内.

Explanation: np.isnan(a) returns a similar array with True where NaN, False elsewhere. .any(axis=1) reduces an m*n array to n with an logical or operation on the whole rows, ~ inverts True/False and a[ ] chooses just the rows from the original array, which have True within the brackets.