【发布时间】:2014-11-03 09:01:09
【问题描述】:
我被一个 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)
我想通过一个函数以编程方式找到这个缺失值,该函数返回一个布尔向量,其中包含与数组中缺失值相对应的元素中的 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) 我可以做些什么来解决这个问题?从错误中,我推测它与其中一个元素的类型不合适有关。解决此问题的最简单方法是什么?
【问题讨论】:
-
我不认为你可以'nan'一个对象
-
你的意思是
isnan一个对象? -
如果您要查找的
nans 仅限于该列,您可以在应用isnan之前对数组进行切片或索引。您也可以考虑使用 structured array 而不是对象数组。
标签: python arrays for-loop numpy nan