重复数组的不同元素不同的次数 [英] Repeat different elements of an array different amounts of times
本文介绍了重复数组的不同元素不同的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个经度数组,lonPorts
Say I have an array with longitudes, lonPorts
lonPort =np.loadtxt('LongPorts.txt',delimiter=',')
例如:
lonPort=[0,1,2,3,...]
而且我想将每个元素重复不同的次数.我该怎么做呢?这是我试过的:
And I want to repeat each element a different amount of times. How do I do this? This is what I tried:
Repeat =[5, 3, 2, 3,...]
lonPort1=[]
for i in range (0,len(lenDates)):
lonPort1[sum(Repeat[0:i])]=np.tile(lonPort[i],Repeat[i])
所以结果是:
lonPort1=[0,0,0,0,0,1,1,1,2,2,3,3,3,...]
我得到的错误是:
list assignment index out of range
我如何摆脱错误并制作我的数组?谢谢!
How do I get rid of the error and make my array? Thank you!
推荐答案
您可以使用 np.repeat()
:
You can use np.repeat()
:
np.repeat(a, [5,3,2,3])
示例:
In [3]: a = np.array([0,1,2,3])
In [4]: np.repeat(a, [5,3,2,3])
Out[4]: array([0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3])
这篇关于重复数组的不同元素不同的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文