如何提取较大的数字Numpy数据类型的位 [英] How to extract the bits of larger numeric Numpy data types

查看:411
本文介绍了如何提取较大的数字Numpy数据类型的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Numpy具有一个库函数np.unpackbits,该函数会将uint8解压缩为长度为8的位向量.是否有相应的快速方法来解压缩较大的数字类型?例如. uint16uint32.我正在研究一个涉及数字之间频繁转换以进行数组索引及其位向量表示的问题,而瓶颈是我们的打包和解压缩功能.

Numpy has a library function, np.unpackbits, which will unpack a uint8 into a bit vector of length 8. Is there a correspondingly fast way to unpack larger numeric types? E.g. uint16 or uint32. I am working on a question that involves frequent translation between numbers, for array indexing, and their bit vector representations, and the bottleneck is our pack and unpack functions.

推荐答案

您可以使用viewunpackbits

输入:

unpackbits(arange(2, dtype=uint16).view(uint8))

输出:

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0]

对于a = arange(int(1e6), dtype=uint16),这在我的计算机上大约7毫秒就非常快

For a = arange(int(1e6), dtype=uint16) this is pretty fast at around 7 ms on my machine

%%timeit
unpackbits(a.view(uint8))

100 loops, best of 3: 7.03 ms per loop

对于字节顺序,您必须查看 http://docs.scipy. org/doc/numpy/user/basics.byteswapping.html ,然后根据需要在其中应用建议.

As for endianness, you'll have to look at http://docs.scipy.org/doc/numpy/user/basics.byteswapping.html and apply the suggestions there depending on your needs.

这篇关于如何提取较大的数字Numpy数据类型的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆