python - 在 dtype obj 的 NumPy 数组中查找缺失值

标签 python arrays for-loop numpy nan

我被一个缺失值的 dtype obj 的 NumPy 数组逼疯了(在下面的例子中,它是倒数第二个值)。

>> a
array([0, 3, 'Braund, Mr. Owen Harris', 'male', 22.0, 1, 0, 'A/5 21171',
       7.25, nan, 'S'], dtype=object)

我想通过一个函数以编程方式找到这个缺失值,该函数返回一个 bool 向量,元素中的 True 值对应于数组中的缺失值(如下例所示)。

>> some_function(a)
array([False, False, False, False, False, False, False, False, False, True, False],
      dtype=bool)

我尝试了 isnan 但没有成功。

>> isnan(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 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''

我还尝试使用 apply_along_axis 对数组的每个元素显式执行操作,但返回相同的错误。

>> apply_along_axis(isnan, 0, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 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''

任何人都可以向我解释 (1) 我做错了什么以及 (2) 我可以做些什么来解决这个问题?从错误中,我了解到它与不属于适当类型的元素之一有关。解决此问题的最简单方法是什么?

最佳答案

另一种解决方法是:

In [148]: [item != item for item in a]
Out[148]: [False, False, False, False, False, False, False, False, False, True, False]

NaNs are not equal to themselves .但是请注意,可以定义自定义对象,如 NaN,不等于它们自身:

class Foo(object):
    def __cmp__(self, obj):
        return -1
foo = Foo()
assert foo != foo

所以使用 item != item 并不一定意味着 item 是 NaN。


请注意,如果可能的话,通常最好避免 dtype object 的 NumPy 数组。

  • 它们不是特别快——对其内容的操作 通常退化为对底层 Python 对象的 Python 调用。正常的 Python 列表通常具有更好的性能。
  • 与比 Python 数字列表更节省空间的数值数组不同,对象数组的空间效率不是特别高,因为每个项目都是一个 对 Python 对象的引用。
  • 它们也不是特别方便,因为许多 NumPy 操作 不适用于 dtype object 的数组。 isnan 就是这样一个例子。

关于python - 在 dtype obj 的 NumPy 数组中查找缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25753110/

相关文章:

python - 让 TRAC 在 IIS7 上运行

python - 开发库模块时设置Python路径

c++ - 这个用于增长数组的 C++ 代码可能会中断吗?

java - java中int数组到Integer数组列表的转换

javascript - 将数组中的元素插入后,它是空的

c# - 使用 if 语句缩短 for 循环 - C#

python - 在python中以随机顺序匹配两个带有字母的字符串

python - 连续输入序列的简单哈希,输出中没有可见的循环

PHP:for 循环两次显示相同的结果而不是两个不同的结果?

c++ - 多变量for循环