如何有效地将numpy.int8数组转换为值转换的numpy.uint8数组?
问题描述:
我有一个大的numpy数组的签名字节(dtype int8
)。它包含全部-128到+127的值。我想通过给每个元素添加128来有效地将其转换为无符号字节数组(dtype uint8
),例如-128→0,0→128,+ 127→255,等所以当然结果仍然是放入一个无符号字节。如何有效地将numpy.int8数组转换为值转换的numpy.uint8数组?
给出了正确的数值结果的简单元素添加,但是除了源数组外,还创建了使用两倍内存(dtype int16
)的结果数组,尽管只需要结果元素的低位字节。
>>> import numpy
>>> a = numpy.array([-128, -1, 0, 1, 127 ], dtype=numpy.int8)
>>> b = a + 128
>>> b
array([ 0, 127, 128, 129, 255], dtype=int16)
有没有办法来控制结果数组的dtype
是uint8
?
就地修改值和数据“铸造”到一个新的类型,这样的替代方法:
>>> for i in xrange(0, 5):
... if a[i] < 0:
... a[i] -= 128
... elif a[i] >= 0:
... a[i] += 128
...
>>> a
array([ 0, 127, -128, -127, -1], dtype=int8)
>>> a.view(dtype=numpy.uint8)
array([ 0, 127, 128, 129, 255], dtype=uint8)
是更有效利用空间,但是非常昂贵的在时间上与所述大阵列Python中的转换。
我该如何快速地进行这种转换?
答
import numpy as np a = np.array([-128, -1, 0, 1, 127], dtype=np.int8) a = a.view(np.uint8) a += 128 print a # -> array([ 0, 127, 128, 129, 255], dtype=uint8)
这不创建副本,并且所有操作都在原地。
EDIT:更安全地先投射到uint ---定义了无符号环绕。 EDIT2:s/numpy/np/g;
答
In [18]: a = numpy.array([-128, -1, 0, 1, 127 ], dtype=numpy.int8)
In [19]: z = a.view(dtype=numpy.uint8)
In [20]: z += 128
In [21]: z
Out[21]: array([ 0, 127, 128, 129, 255], dtype=uint8)
我希望我没有误解要求。
谢谢。我没有想到利用无符号的环绕结合add-assign运算符来控制总和结果的类型。 –