gpt4 book ai didi

python - 重复值 n 次,n 在一个数组中

转载 作者:行者123 更新时间:2023-12-05 08:25:33 25 4
gpt4 key购买 nike

我有一个值数组 a,其值在每个索引 idx 我想重复一定数量 b[idx]次,在另一个数组 (b) 中的相同索引 idx 处给出,如下所示:

a = numpy.array([1, 2, 3 ,4, 5])
b = numpy.array([2, 3, 1, 2, 4])

期望的输出:

c = numpy.array([1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5])

我意识到我可以做这样的事情:

len_a = numpy.shape(a)[0]
sum_b = sum(b)
c = numpy.zeros((1, 0))
for idx in range(len_a):
repeated_a = numpy.repeat(a[idx], b[idx])
repeated_a = numpy.reshape(repeated_a, (1, numpy.shape(repeated_a)[0]))
c = numpy.hstack((c, repeated_a))

但是,循环不是一个好的选择,因为它很慢。我该怎么做才能让它更快?也许是某种形式的矢量化。

最佳答案

您正在寻找为此目的而制作的内置重复功能。只需将两个数组都输入函数即可:

np.repeat(a,b)
#[1 1 2 2 2 3 4 4 5 5 5 5]

关于python - 重复值 n 次,n 在一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64216057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com