Skip to main content
 首页 » 编程设计

python之根据另一个索引数组重复 numpy 数组元素

2025年05月04日17fff_TT

我有以下占位符数组:

placeholder = np.zeros(10) 

A 包含我想要进入占位符的值

A = np.array([25, 40, 65,50]) 

idx 具有占位符的索引(请注意,这与 A 具有相同的形状)

idx = np.array([0, 5, 6, 8]) 

问题:

我想用 A 的元素填充 placeholder。 A 中元素的重复次数由 idx 数组的间隔长度定义。

比如25重复5次,因为对应的索引范围是[0, 5)。 65重复了两次,因为对应的索引范围是[6,8)

预期输出:

np.array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50]) 

请您参考如下方法:

使用 np.diff + np.repeat 快速简单:

repeats = np.diff(np.append(idx, len(placeholder))) 
 
A.repeat(repeats) 
array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])