I have a list as such
li=[2,4,5,7,8,9,10,26,23,28,11,3,17,10]
I want to create a new column in my dataframe such that 1st value in the list is repeated 8 times, the second value is repeated 8 times, the third is repeated 8 times, the 4th is repeated 9 times, the 5th 9 times, the 6th 9 times and the 7th 7 times.
The next seven values should repeat in the same pattern of numbers and then the next seven values, this goes on till the end of the df.
How can I achieve this?
I looked up np.repeat but I'm not sure how to achieve this for varying n.
Example output
values
2
2
2
2
2
2
2
2
4
4
4
4
4
4
4
4
5
5
5
5
5
5
5
5
7
7
7
7
7
7
7
.
.
CodePudding user response:
You can just do div add 1
rep = [8,8,8,9,9,9,7]
np.repeat(li,(rep * (len(li)//len(rep) 1)) [:len(li)])
CodePudding user response:
np.repeat can take a list of repeat counts, so you can np.tile to generate the repeat counts and np.repeat to do them:
>>> li = [2,4,5,7,8,9,10,26,23,28,11,3,17,10]
>>> repeats = [8,8,8,9,9,9,7]
>>> np.repeat(li, np.tile(repeats, len(li))[:len(li)])
array([ 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4, 5,
5, 5, 5, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8,
8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 10, 10, 26, 26, 26, 26, 26, 26, 26, 26, 23, 23,
23, 23, 23, 23, 23, 23, 28, 28, 28, 28, 28, 28, 28, 28, 11, 11, 11,
11, 11, 11, 11, 11, 11, 3, 3, 3, 3, 3, 3, 3, 3, 3, 17, 17,
17, 17, 17, 17, 17, 17, 17, 10, 10, 10, 10, 10, 10, 10])
