【问题标题】:How to remove nan values from numpy.ndarray如何从 numpy.ndarray 中删除 nan 值
【发布时间】:2019-11-11 17:07:49
【问题描述】:

我有一些 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 isnull 吗?这可能有效

标签: python python-3.x nan numpy-ndarray


【解决方案1】:

这可能是因为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)

【讨论】:

  • 得到我上面提到的带有字符串值的数组的错误。
【解决方案2】:

pandas 中有一个名为pandas.DataFrame.dropna 的函数,它会删除所有具有nan 值的列。如果您没有创建 DataFrame,请创建,然后执行 df.dropna()

【讨论】:

  • 我不想删除具有 nan 值的列。我只想删除 nan 值,看看每列还剩下什么。
  • 如果您正在写一些东西作为答案,请编写代码并在之前检查它。如果只是“希望对您有所帮助”,请使用 cmets 部分。
猜你喜欢
  • 2018-09-23
  • 2023-03-26
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2022-11-15
相关资源
最近更新 更多