如何使用Numpy在指定位置嵌入数组或添加零行
Numpy数组指定位置填充与插入零行的实现
一、从已有零数组填充得到目标数组c
已知原始数组a和零数组b,可通过索引直接赋值将a的元素放到b对应位置,快速得到目标数组c:
import numpy as np # 定义原始数组 a = np.array([[1], [2], [3], [4], [5]]) # 创建8行1列的零数组 b = np.zeros((8, 1)) # 将a的前3个元素赋值给b的第2-4行(索引2到5,左闭右开) b[2:5] = a[:3] # 将a的后2个元素赋值给b的第6-7行 b[6:] = a[3:] c = b print(c)
执行后输出结果:
[[0.] [0.] [1.] [2.] [3.] [0.] [4.] [5.]]
二、在指定位置插入零行
如果需要直接在原始数组a的指定位置插入零行,可使用Numpy的np.insert()方法按行操作:
import numpy as np a = np.array([[1], [2], [3], [4], [5]]) # 指定要插入零行的位置(相对于原数组的索引) insert_positions = [0, 1, 3] # 创建对应数量的零行 zeros_rows = np.zeros((len(insert_positions), 1)) # axis=0表示按行插入 c = np.insert(a, insert_positions, zeros_rows, axis=0) print(c)
这里的insert_positions对应原数组索引逻辑:
- 索引0、1:在原数组开头插入两个零行
- 索引3:在原数组第3个元素(即
[4])之前插入零行,正好匹配目标数组倒数第3行的位置
执行后同样会得到目标数组c。
内容的提问来源于stack exchange,提问作者Yurii Yarema
相关产品推荐
相关产品推荐

