我被一个缺失值的 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/