首页 > 编程笔记 > Python笔记 阅读:18

NumPy frombuffer()函数的用法(附带实例)

NumPy 的 ndarray 数组对象不能像 Python 列表一样动态地改变大小,在做数据采集时很不方便。下面介绍如何通过 frombuffer() 函数创建动态数组。

frombuffer() 函数接受 buffer 输入参数,以流的形式将读入的数据转换为数组。frombuffer() 函数语法格式如下:
numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)
参数说明:
【实例】将字符串“https://c.biancheng.net”转换为数组,程序代码如下:
import numpy as np
n = np.frombuffer(b'https://c.biancheng.net', dtype='S1')
print(n)
在上述代码中,当 buffer 参数的值为字符串时,Python3 默认字符串是 Unicode 类型的,所以要将其转成 Bytestring 类型,需要在原字符串前加上“b”。

相关文章