如何从 numpy.ndarray 中删除 nan 值
How to remove nan values from numpy.ndarray
我有一些 numpy.ndarray 变量。它们包括 nan 值,我想从它们中删除每个 nan 值。数组包含 int、float、str 等值。这些数组的示例:
['A' 'B' 'C' 'D' nan 'E' 'F']
另一个:
[nan 1.]
并且可能存在数组包含 float、str 和 nan 值的情况。在这种情况下,我怎样才能只删除 nan 值?
我使用了以下代码:
x[:, ~np.isnan(x).any(axis=0)]
并得到以下错误:
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''
pandas 中有一个名为 pandas.DataFrame.dropna
的函数,它删除所有具有 nan
值的列。如果没有,只需创建 DataFrame,然后执行 df.dropna()
.
这可能是因为 np.isnan()
无法处理集合中可能的元素类型中的字符串类型。您可以尝试使用 panda's
isnull()
删除 NaN
值。
import pandas as pa
import numpy as np
a = ['A', np.nan, np.nan, 1.67, 8]
a = [x for x in a if not pa.isnull(x)]
print(a)
我有一些 numpy.ndarray 变量。它们包括 nan 值,我想从它们中删除每个 nan 值。数组包含 int、float、str 等值。这些数组的示例:
['A' 'B' 'C' 'D' nan 'E' 'F']
另一个:
[nan 1.]
并且可能存在数组包含 float、str 和 nan 值的情况。在这种情况下,我怎样才能只删除 nan 值?
我使用了以下代码:
x[:, ~np.isnan(x).any(axis=0)]
并得到以下错误:
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''
pandas 中有一个名为 pandas.DataFrame.dropna
的函数,它删除所有具有 nan
值的列。如果没有,只需创建 DataFrame,然后执行 df.dropna()
.
这可能是因为 np.isnan()
无法处理集合中可能的元素类型中的字符串类型。您可以尝试使用 panda's
isnull()
删除 NaN
值。
import pandas as pa
import numpy as np
a = ['A', np.nan, np.nan, 1.67, 8]
a = [x for x in a if not pa.isnull(x)]
print(a)