Duplicate the rows of the numpy array, where the number of duplicates changes

While there is a numpy array for which you want to duplicate each value a certain number of times:

np.array([1,2,3,4]) 

and a second array that determines the number of duplicates desired for each corresponding index position in the original array:

 np.array([3,3,2,2]) 

How do you make:

 [1,1,1,2,2,2,3,3,4,4] 

Obviously, you can use iteration to create a new array, but I'm curious if there is a more elegant numpy based solution.

+4
source share
1 answer

Use numpy.repeat :

 >>> numpy.repeat([1,2,3,4], [3,3,2,2]) array([1, 1, 1, 2, 2, 2, 3, 3, 4, 4]) 
+3
source

Source: https://habr.com/ru/post/1501593/


All Articles