python - 用 0 错误 :nan not supported for input type 替换 nan

标签 python numpy

我有一个包含日期和时间的 numpy 数组,如下所示

a[0]=2014-06-01 03:14:34

我检查了 a[0] 的类型。它被指定为 str。numpy 数组中的某些值是 nan。我必须用 0 替换 nan 并用 1 替换 rest。我尝试了 isnan(a) 但它给了我错误: TypeError: 输入类型不支持 ufunc 'isnan',根据转换规则 ''safe'' 无法将输入安全地强制转换为任何受支持的类型 哪里出了问题,如何用 0 替换 nan?

最佳答案

为了使您的数组同时包含字符串和 NaN,它必须是对象数据类型。 object dtype 的 NumPy 数组在内存或性能方面并不是特别有效。 对象数组没有矢量化操作。错误信息

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''

是说 np.isnan 不能应用于对象数组,而这个对象 无法将数组强制转换为受支持的数据类型,例如 np.float

理想情况下,首先要避免构建对象数组。但鉴于你 有这个对象数组,要构建新数组,你不妨循环 列表推导中 a 中的项目:

import numpy as np
a = np.array(['2014-06-01 03:14:34', np.nan], dtype='O')
b = np.array([item == item for item in a]).astype(int)
print(b)

产量

[1 0]

item == item 如何测试 NaN:

NaN 有 the property that NaN != NaN . NaN 是标准 Python 对象万神殿中唯一具有此属性的对象。可以定义自定义类,其实例也可以具有此属性。只要 a 不包含此类自定义类的实例,您就可以使用 item != item 属性来测试 NaN:

In [43]: float('nan') != float('nan')
Out[43]: True

In [44]: np.nan != np.nan
Out[44]: True

关于python - 用 0 错误 :nan not supported for input type 替换 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31941532/

相关文章:

python - 是否有将整数转换为第一/第二/第三的库

python - 如何获取第一个大写字母,然后在 Python 中获取每个大写字母后面没有的另一个大写字母?

python - 当requirements.txt中提到pip包时,如何通过--no-build-isolation安装它们?

Python - 合并许多形状未知的大numpy数组,这些数组不适合内存

Python Pandas : Convert 2, 000,000 DataFrame 行到二进制矩阵 (pd.get_dummies()) 没有内存错误?

python - 如何使用 Python 3.5 通过 SSH 隧道连接到 MySQL 数据库?

python - 转置 Pandas 数据透视表

python - 为什么 numpy select 比通过 apply 方法的自定义函数慢?

python - 使用 numpy 保存带有预定义分隔符的按行 txt

python - 如何在 numpy 数组中找到相同的实体?