Python 如何有效地将numpy.int8数组转换为值移位的numpy.uint8数组?

Python 如何有效地将numpy.int8数组转换为值移位的numpy.uint8数组?,python,numpy,Python,Numpy,我有一个有符号字节的大numpy数组(dtype int8)。它包含的值的完整范围为-128到+127。我希望通过在每个元素中添加128,从而有效地将元素转换为无符号字节数组(dtype uint8)→ 0, 0 → 128, +127 → 255等。因此,结果当然仍然适合无符号字节 简单的元素加法给出了正确的数值结果,但是除了源数组之外,还使用两倍的内存(dtype int16)创建一个结果数组,即使只需要结果元素的低字节 >>> import numpy >>&

我有一个有符号字节的大numpy数组(
dtype int8
)。它包含的值的完整范围为-128到+127。我希望通过在每个元素中添加128,从而有效地将元素转换为无符号字节数组(
dtype uint8
)→ 0, 0 → 128, +127 → 255等。因此,结果当然仍然适合无符号字节

简单的元素加法给出了正确的数值结果,但是除了源数组之外,还使用两倍的内存(
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)
xrange(0,5)中的i的
>:
...     如果a[i]<0:
...         a[i]=128
...     如果a[i]>=0:
...         a[i]+=128
...
>>>a
数组([0,127,-128,-127,-1],dtype=int8)
>>>a.view(dtype=numpy.uint8)
数组([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) 将numpy作为np导入 a=np.array([-128,-1,0,1127],dtype=np.int8) a=a.view(np.uint8) a+=128 打印 #->数组([0,127,128,129,255],dtype=uint8) 这不会创建副本,并且所有操作都已就绪

编辑:首先强制转换到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操作符来控制sum结果的类型。