【发布时间】:2020-09-29 19:53:33
【问题描述】:
我需要一个包含不同数据类型(浮点数或整数)列的表。
我使用 dtype 来定义它们:
import numpy as np
# define array
datadef=[ ('i', '<i4'), ('f', '<f8'), ('g', '<f8'), ('j', '<i4') ]
arr = np.full((4,), np.nan, dtype=datadef)
# fill array with data
arr['i'] = np.array([1, 2, 3, 4])
arr['f'] = np.array([1.3333333333, np.nan, 2.6666666666666666, 5.0])
arr['g'] = np.array([2.77777777777, 5.4, 3.4, np.nan])
# nothing for 'j'
print arr
输出:
[(1, 1.33333333, 2.77777778, -2147483648)
(2, nan, 5.4 , -2147483648)
(3, 2.66666667, 3.4 , -2147483648)
(4, 5. , nan, -2147483648)]
最后一列的NaN值已经转换为-2147483648,目前没有问题。
但现在我无法检查数组中的值是否确实为 NaN:
row = arr[1]
print np.isnan(row) # 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''
在单个单元格上,NaN 信息似乎丢失了,-2147483648 被视为“经典数字”:
print row # (2, nan, 5.4, -2147483648)
print np.isnan(row[0]) # False, OK
print np.isnan(row[1]) # True, OK
print np.isnan(row[3]) # False, expected True
在这种情况下,有没有一种简单的方法可以检查整数上的NaN 吗?
【问题讨论】:
-
numpy 中没有整数的 NaN:参见例如stackoverflow.com/questions/12708807/numpy-integer-nan 。但熊猫似乎有一个扩展:stackoverflow.com/questions/11548005/…
标签: python python-2.7 numpy nan