NumPy(Numerical Python的缩写)是一个开源的Python科学计算库。使用NumPy,就可以很自然地使用数组和矩阵。NumPy包含很多实用的数学函数,涵盖线性代数运算、傅里叶变换和随机数生成等功能。本文主要介绍一下NumPy中frombuffer方法的使用。

numpy.frombuffer

numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)

将缓冲区解释为一维数组。

参数:

buffer :buffer_like

公开缓冲区接口的对象。

dtype :data-type, 可选

返回array的数据类型;默认值:float。

countint, 可选

要阅读的条目数。-1表示缓冲区中的所有数据。

offsetint, 可选

从这个偏移量(以字节为单位)开始读取缓冲区;默认值:0

Notes

如果缓冲区中的数据不是机器字节顺序的,则应将其指定为数据类型的一部分,例如:

>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder('>')
>>> np.frombuffer(buf, dtype=dt) 

结果数组的数据将不会被字节包装,但是将被正确地解释

例子

>>> s = b'hello world'
>>> np.frombuffer(s, dtype='S1', count=5, offset=6)
array([b'w', b'o', b'r', b'l', b'd'], dtype='|S1')

>>> np.frombuffer(b'\x01\x02', dtype=np.uint8)
array([1, 2], dtype=uint8)
>>> np.frombuffer(b'\x01\x02\x03\x04\x05', dtype=np.uint8, count=3)
array([1, 2, 3], dtype=uint8)


推荐文档

相关文档

大家感兴趣的内容

随机列表