我有一个很大的numpy数组的有符号字节(dtype int8).它包含-128到+127范围内的全部值.我想dtype uint8通过向每个元素添加128来有效地将有效转换为无符号字节数组(),例如-128→0,0→128,+ 127→255 等.所以当然结果仍然适合于无符号字节.
给定正确的数字结果的简单元素添加,但dtype int16除了源数组之外,使用两倍的memory()创建结果数组,即使只需要结果元素的低字节.
>>> 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)
Run Code Online (Sandbox Code Playgroud)
有没有办法控制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)
Run Code Online (Sandbox Code Playgroud)
对于使用Python进行转换的大型数组而言,它的空间效率更高,但成本更高.
如何快速地进行这种转换?
pv.*_*pv. 14
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)
这不会创建副本,并且所有操作都是就地的.
编辑:更安全地首先施放到uint ---定义了无符号环绕. EDIT2:s/numpy/np/g;
| 归档时间: |
|
| 查看次数: |
9931 次 |
| 最近记录: |