NumPy frombuffer()

frombuffer() 方法将缓冲区解释为一维数组。

示例

# byte string behaves like a buffer buf = b'HelloWorld'
# import numpy import numpy as np
# load from the buffer array1 = np.frombuffer(buf, dtype = 'S1')
print(array1) # Output : [b'H' b'e' b'l' b'l' b'o' b'W' b'o' b'r' b'l' b'd']

frombuffer() 语法

frombuffer() 的语法是

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

frombuffer() 参数

frombuffer() 方法接受以下参数

  • buffer - 要读取的缓冲区 (buffer_like)
  • dtype(可选)- 输出数组的类型(dtype
  • count(可选) - 要读取的项目数 (int)
  • offset(可选) - 从该偏移量开始读取缓冲区 (int)
  • like(可选) - 用于创建非 NumPy 数组的引用对象 (array_like)

注意: count 的默认值是 -1,表示缓冲区中的所有数据。


frombuffer() 返回值

frombuffer() 方法从缓冲区返回一个数组。


示例 1:使用 frombuffer() 创建数组

# byte string behaves like a buffer
buf = b'HelloWorld'

# import numpy
import numpy as np
# load from buffer with element size 2 array1 = np.frombuffer(buf, dtype = 'S2')
print(array1)
# load from buffer with element size 3 array2 = np.frombuffer(buf, dtype = 'S3')
print(array2)

输出

[b'He' b'll' b'oW' b'or' b'ld']
ValueError: buffer size must be a multiple of element size

这里,缓冲区的长度是 10。对于 array1,元素的大小是 2,这意味着它可以将缓冲区划分为 5 个元素。

然而,对于 array210 不是 3 的倍数。因此,无法创建数组。


示例 2:使用 dtype 参数指定数据类型

dtype 参数有助于指定创建的 numpy 数组所需的数​​据类型。

# byte string behaves like a buffer
buf = b'\x01\x02\x03\x04'

# import numpy
import numpy as np

# load from the buffer as int8 array1 = np.frombuffer(buf, dtype = np.uint8)
print(array1)
# load from the buffer as int16 array2 = np.frombuffer(buf, dtype = np.uint16)
print(array2)

输出

[1 2 3 4]
[ 513 1027]

要理解输出,我们需要了解缓冲区的工作原理。由于本教程是关于 NumPy 而不是缓冲区的,因此我们不会深入探讨。但是,您可以访问官方 Python 文档

首先,\x 代表十六进制格式。

dtype = np.unit8 时,字节字符串中的每个字节被解释为 8 位无符号整数。因此,array1 变为 [1 2 3 4]

dtype = np.unit16 时,字节字符串中的字节对被解释为 16 位无符号整数。因此,array2 有 2 个元素 \x01\x022 * 256 + 1 = 513\x03\x044 * 256 + 3 = 1027,变成 [513 1027]


示例 3:使用 count 参数限制要读取的数据

count 参数有助于指定要从缓冲区读取的项目数。

# byte string behaves like a buffer
buf = b'\x01\x02\x03\x04'

# import numpy
import numpy as np

# load the first 2 items from the buffer array1 = np.frombuffer(buf, dtype = np.uint8, count = 2)
print(array1)
# load the first 3 items from the buffer array2 = np.frombuffer(buf, dtype = np.uint8, count = 3)
print(array2)

输出

[1 2]
[1 2 3]

示例 3:使用 offset 参数指定缓冲区偏移量

offset 参数有助于指定在开始从缓冲区读取之前要跳过的项目数。

# byte string behaves like a buffer
buf = b'\x01\x02\x03\x04'

# import numpy
import numpy as np

# load the first 2 items from the buffer with no offset array1 = np.frombuffer(buf, dtype = np.uint8, count = 2) # load 2 items from the buffer after skipping the first item array2 = np.frombuffer(buf, dtype = np.uint8, count = 2, offset = 1) # load 2 items from the buffer after skipping the first 2 items array3 = np.frombuffer(buf, dtype = np.uint8, count = 2, offset = 2)
print(array1) print(array2) print(array3)

输出

[1 2]
[2 3]
[3 4]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战