我有一个32位整数的numpy数组,我想将它转换为16位整数。
我可以使用astype轻松地做到这一点,但是当我对MSB感兴趣时,它似乎总是选择LSBytes
a=np.array([65536],dtype=np.int32) a.astype(np.uint16) >>> array([0], dtype=uint16)我可以通过首先做正确的转换得到我想要的东西:
np.right_shift(a,16).astype(np.uint16) >>> array([1], dtype=uint16)但这似乎效率很低。
我已经阅读了关于astype的文档,并尝试了所有的转换选项,但我找不到任何东西。
I have an a numpy array of 32bit integers and I want to convert it to 16bit integers.
I can easily do this using astype however it appears that this always selects the LSBytes while I am interested in the MSBs
a=np.array([65536],dtype=np.int32) a.astype(np.uint16) >>> array([0], dtype=uint16)I can get what I want by doing a right shift first as such:
np.right_shift(a,16).astype(np.uint16) >>> array([1], dtype=uint16)but this seems rather inefficient.
I have read the documentation on astype and tried all of the casting options but nothing does what I am looking for.
最满意答案
您可以创建32位数组的16位“视图”,然后使用切片查看更高阶的单词。
例如,在a ,低16位包含10,11,12,13,14,15,16,17,高16位包含0,1,2,3,4,5,6,7:
In [47]: a = np.arange(0, 8, dtype=np.int32)*2**16 + np.arange(10, 18, dtype=np.int32) In [48]: a Out[48]: array([ 10, 65547, 131084, 196621, 262158, 327695, 393232, 458769], dtype=int32)b是一个包含16个值的数组,其中包含a的高16位。 (这假设字节顺序是little-endian 。)
In [49]: b = a.view(np.uint16)[1::2] In [50]: b Out[50]: array([0, 1, 2, 3, 4, 5, 6, 7], dtype=uint16)因为.view()方法和切片不复制数组的数据,所以b是与a相同的内存缓冲区的视图。 如果你就地改变了b ,你也会改变a 。
请注意,这不会对数字进行舍入。 32位数65535的高16位将为0。
此外,这可能无法按您想要的方式处理负值。
You can create a 16 bit "view" of the 32 bit array, and then use a slice to view just the higher order word.
For example, in a, the lower 16 bits contain 10, 11, 12, 13, 14, 15, 16, 17, and the higher 16 bits contain 0, 1, 2, 3, 4, 5, 6, 7:
In [47]: a = np.arange(0, 8, dtype=np.int32)*2**16 + np.arange(10, 18, dtype=np.int32) In [48]: a Out[48]: array([ 10, 65547, 131084, 196621, 262158, 327695, 393232, 458769], dtype=int32)b is an array of 16 values containg the higher 16 bits from a. (This assumes the byte order is little-endian.)
In [49]: b = a.view(np.uint16)[1::2] In [50]: b Out[50]: array([0, 1, 2, 3, 4, 5, 6, 7], dtype=uint16)Because the .view() method and slices to not copy the array's data, b is a view into the same memory buffer as a. If you change b in-place, you will also change a.
Note that this does not round the numbers. The high 16 bits of the 32 bit number 65535 will be 0.
Also, this might not handle negative values the way that you want.
更多推荐
发布评论