如何初始化NumPy数组并使用固定序列预填充为指定形状?
NumPy数组初始化与固定序列填充问题
想初始化一个NumPy数组,并用固定序列[0,1,2,...,9]预填充成5行10列的二维数组,尝试用fill方法时出现报错,具体操作及错误信息如下:
>>> import numpy as np >>> c = np.empty(5) >>> c array([0.0e+000, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323]) >>> np.array(list(range(0,10,1))) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> c.fill(np.array(list(range(0,10,1)))) TypeError: only length-1 arrays can be converted to Python scalars The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: setting an array element with a sequence. >>> c.fill([np.array(list(range(0,10,1)))]) TypeError: float() argument must be a string or a real number, not 'list' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: setting an array element with a sequence.
期望得到的结果:
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
问题原因
np.empty(5)创建的是一维数组,每个元素为标量类型;而fill方法仅支持传入单个标量值,无法直接处理长度大于1的数组或序列,因此触发类型错误。同时你需要的是二维数组,初始创建的数组形状本身就不符合需求。
解决方法
方法1:先创建正确形状的数组,再广播赋值
import numpy as np # 创建5行10列的空数组 c = np.empty((5, 10)) # 定义要填充的目标序列 target_seq = np.arange(10) # 利用NumPy广播特性,将每行赋值为目标序列 c[:] = target_seq
方法2:用np.tile复制序列
tile函数可将目标序列重复指定次数,直接生成所需数组:
target_seq = np.arange(10) c = np.tile(target_seq, (5, 1)) # (5,1)表示沿行方向重复5次,列方向重复1次
方法3:用np.full结合广播
full函数可直接创建指定形状的数组,并用目标序列填充(依赖广播机制):
c = np.full((5, 10), np.arange(10))
以上三种方法都能生成你期望的二维数组。
内容的提问来源于stack exchange,提问作者Majoris
相关产品推荐
相关产品推荐

