NumPy - 从现有数据创建数组
NumPy - 从现有数据创建数组
Section titled “NumPy - 从现有数据创建数组”NumPy 提供了几个函数,可以基于现有数据结构(如 Python 列表 (list)、元组 (tuple) 或原始内存缓冲区 (buffer))创建新的数组。
numpy.asarray()
Section titled “numpy.asarray()”此函数将各种 Python 序列类型(列表、元组、元组列表等)转换为 NumPy N维数组 (ndarray)。它类似于 numpy.array(),但如果输入已经是具有所需 数据类型 (dtype) 的 ndarray,asarray() 会避免创建副本。
numpy.asarray(a, dtype=None, order=None)参数:
| 参数 | 描述 |
|---|---|
| a | 输入数据,通常是 Python 列表 (list)、元组 (tuple) 或其他序列。 |
| dtype | 可选参数。输出数组所需的数据类型。如果未指定,NumPy 会从输入数据中推断。 |
| order | 可选参数。内存布局:‘C’ (行主序,默认) 或 ‘F’ (列主序)。 |
当你需要确保拥有一个 ndarray,并且希望在输入数据已经合适时避免不必要的数据复制时,使用 asarray()。
示例 1: 将列表转换为 ndarray
Section titled “示例 1: 将列表转换为 ndarray”Python 列表的基本转换。
import numpy as np
my_list = [1, 2, 3]a = np.asarray(my_list)
print(a)print(type(a))输出:
[1 2 3]<class 'numpy.ndarray'>示例 2: 指定 dtype
Section titled “示例 2: 指定 dtype”转换列表并设置数据类型为浮点型。
import numpy as np
my_list = [1, 2, 3]a = np.asarray(my_list, dtype=float)
print(a)print(a.dtype)输出:
[1. 2. 3.]float64示例 3: 将元组转换为 ndarray
Section titled “示例 3: 将元组转换为 ndarray”Python 元组的转换方式类似。
import numpy as np
my_tuple = (1, 2, 3)a = np.asarray(my_tuple)
print(a)输出:
[1 2 3]示例 4: 转换元组列表
Section titled “示例 4: 转换元组列表”如果内部序列长度不同,生成的数组的数据类型 dtype 将是 object。
import numpy as np
list_of_tuples = [(1, 2, 3), (4, 5)] # 注意: 内部元组长度不同a = np.asarray(list_of_tuples)
print(a)print(a.dtype)输出:
[(1, 2, 3) (4, 5)]objectnumpy.frombuffer()
Section titled “numpy.frombuffer()”此函数通过直接解释 缓冲区 (buffer) 对象(如字节 bytes)中的数据来创建一个一维 ndarray,无需复制数据。这对于处理二进制数据或与底层库进行接口操作很有用。
numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)参数:
| 参数 | 描述 |
|---|---|
| buffer | 导出缓冲区接口的对象(例如,bytes、bytearray)。 |
| dtype | 从缓冲区解释的元素的数据类型。 |
| count | 要读取的项数。-1 (默认) 表示尽可能多地读取。 |
| offset | 从此偏移量 (以字节为单位) 开始读取缓冲区。 |
示例: 从字节创建数组
Section titled “示例: 从字节创建数组”将字节字符串解释为单字节字符数组。
import numpy as np
# 创建一个字节字符串 (注意开头的 'b')s = b'Hello World'
# 将缓冲区解释为 1 字节字符串 ('S1') 的数组a = np.frombuffer(s, dtype='S1')
print(a)输出:
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']注意: 修改通过 frombuffer 创建的数组 会 修改原始缓冲区,如果该缓冲区是可变的(例如 bytearray)。
numpy.fromiter()
Section titled “numpy.fromiter()”此函数通过使用任何 Python 可迭代对象 (iterable)(例如生成器 generator、列表 list、范围对象 range)中的项来创建一个一维 ndarray。对于大型序列,这可以节省内存,因为它不需要整个序列一次性存在于内存中(如果可迭代对象逐个生成项的话)。
numpy.fromiter(iterable, dtype, count=-1)参数:
| 参数 | 描述 |
|---|---|
| iterable | 任何可以迭代的 Python 对象。 |
| dtype | 结果数组的数据类型。这 必须 指定。 |
| count | 从迭代器读取的项数。-1 (默认) 表示使用所有项。 |
首先,我们来看一个使用 range() 创建的标准 Python 列表。
示例 1: 使用 Python range
Section titled “示例 1: 使用 Python range”# 在 Python 3 中使用 range 创建一个标准 Python 列表# (range 本身是一个可迭代对象,list() 会使用它)my_list = list(range(5))print(my_list)输出:
[0, 1, 2, 3, 4]示例 2: 将 fromiter 与 range 结合使用
Section titled “示例 2: 将 fromiter 与 range 结合使用”直接从 range 可迭代对象创建 ndarray。
import numpy as np
# 创建一个可迭代对象 (range 对象)iterable = range(5)
# 使用迭代器创建一个 float dtype 的 ndarrayx = np.fromiter(iterable, dtype=float)
print(x)print(x.dtype)输出:
[0. 1. 2. 3. 4.]float64