首页 > 解决方案 > 错误转换为 int32 ?期待 uint16 代替?

问题描述

为什么在第二种情况下 numpy 会错误地转换为int32?我必须使用第二种情况,因为我使用了一个变量..

In [24]: np.zeros(10,dtype=np.uint16) - 1
Out[24]: array([65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535], dtype=uint16)



In [23]: np.zeros(10,dtype=np.uint16) + (-1)
Out[23]: array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1], dtype=int32)

In [26]: np.zeros(10,dtype=np.uint16) + np.uint16(-1)
Out[26]: array([65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535], dtype=uint16)

标签: pythonnumpycasting

解决方案


这不一定是错误的转换,numpy是试图找到可以处理所有可能结果的最小类型。

您可以找出结果的类型np.result_type

np.result_type(np.uint16, -1)

>>> int32

np.result_type(np.uint16, 1)

>>> uint16

使用np.zeros(10,dtype=np.uint16) + np.uint16(-1),结果将是uint16,这是您需要执行的强制无符号结果的操作。否则,numpy将假定必须强制转换结果以处理负值。


推荐阅读