将int64转换为uint64
我想把一个 int64 的 numpy 数组转换成 uint64 的 numpy 数组,同时在这个过程中给每个值加上 2 的 63 次方,这样它们仍然在数组允许的有效范围内。举个例子,如果我从
a = np.array([-2**63,2**63-1], dtype=np.int64)
开始,我想得到
np.array([0.,2**64], dtype=np.uint64)
乍一看这似乎很简单,但实际上你该怎么做呢?
2 个回答
1
我不是numpy的专家,但这个:
>>> a = np.array([-2**63,2**63-1], dtype=np.int64)
>>> b = np.array([x+2**63 for x in a], dtype=np.uint64)
>>> b
array([ 0, 18446744073709551615], dtype=uint64)
在Python 2.6和numpy 1.3.0下对我来说是有效的。
我想你在预期的输出中应该是指2**64-1
,而不是2**64
,因为2**64
放不进一个uint64类型里。(18446744073709551615是2**64-1
)
3
使用 astype() 方法可以把数值转换成另一种数据类型:
import numpy as np
(a+2**63).astype(np.uint64)
# array([ 0, 18446744073709551615], dtype=uint64)