python - 将 numpy 数组写入具有可变整数精度的二进制文件

标签 python numpy bitstring

我想将 numpy 数组写入二进制文件,但我想对整数使用非标准大小编码。例如,一些int数组将作为3位整数写入文件,一些作为7位,一些作为13位...

我已经看到有一个 numpy 方法 tofile() 但它仅适用于给定的数组数据类型,即 int8、int16、int32 等。(Reference)

我如何将其写入具有可变位长度的文件?

最佳答案

举一个位串的具体例子:

>>> from bitstring import Bits
>>> a = [3,1,2,6,4,10]  # some unsigned integers to encode
>>> p = 5               # number of bits of precision to use

现在从每个整数创建 5 位位串并将它们连接在一起:

>>> b = Bits().join(Bits(uint=x, length=p) for x in a)
>>> b
Bits('0b000110001000001001100010001010')

它可以转换为字节,但请注意,如果需要,它将用零位填充到字节边界。写入文件时,您总是会拥有整数字节,这就是文件系统的工作方式:

>>> b.tobytes()
'\x18\x82b('    

要再次解码,有很多选项,但由于所有内容的长度都相同,cut 方法很有用:

>>> [x.uint for x in b.cut(p)]
[3, 2, 1, 6, 4, 10]

参见the docs了解更多信息。就效率而言,对于纯Python来说应该相当不错了。如果您确实需要更快的速度,请尝试使用 bitarray 模块,它是用 C 实现的,应该能够同样很好地处理这个问题。

关于python - 将 numpy 数组写入具有可变整数精度的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17043986/

相关文章:

python - 在没有循环的 Numpy 中添加子矩阵

matlab - 将 Matlab 函数结果缓存到文件

python - 通过等待用户按键来暂停循环的最简单方法是什么?

python - 在查询 pandas dataframe 列值时使用类似 MySQL 的条件

python - dev_appserver.py app.yaml 生成 : ImportError: Importing the multiarray numpy extension module failed

python - 使用 python 将比特流保存到文件

python - Scapy 导入错误 'socket.gaierror: [Errno 11001] getaddrinfo failed'

python - 使用 for 循环填充时不显示 matplotlib 散点图

python - pd.read_hdf 抛出 'cannot set WRITABLE flag to True of this array' 和 'No module named ' numpy.core._multiarray_umath'