np.uint16 与 np.uint16 不同



我正在尝试使用字典查找将numpy dtypes映射到关联的值。我观察到以下违反直觉的行为:

dtype = np.uint16
x = np.array([0, 1, 2], dtype=dtype)
assert x.dtype == dtype
d = {np.uint8: 8, np.uint16: 16, np.uint32: 32, np.float32: 32}
print(dtype in d)  # prints True
print(x.dtype in d)  # prints False

使用其他 dtype 会产生类似的结果。

所以我们有那个np.uint16 == x.dtype,但前者在字典的键中找到,而后者则不是。任何解释和/或简单的解决方法将不胜感激。

Dtypes 不像乍一看那样工作。np.uint16不是dtype 对象。它只是可以转换为一个。np.uint16是一个 type 对象,表示 uint16 dtype 的数组标量类型。

x.dtype是一个实际的 dtype 对象,dtype 对象以一种奇怪的方式实现==,这种方式是不可传递的,与hash不一致。dtype == other基本上是dtype == np.dtype(other)实现的,当other还不是dtype时。您可以在源中查看详细信息。

特别是,x.dtype等于np.uint16,但它没有相同的哈希,因此字典查找找不到它。

x.dtype返回一个dtype对象(请参阅 dtype 类(

要获取内部类型,您需要调用x.dtype.type

print(x.dtype.type in d) # True

这是预期的行为:

np.uint16是未初始化的,因此dtype实际上是一个类,而x.dtype实际上是一个数据类型对象(文档(。

另一个答案显示了此处的解决方法。

最新更新