Reputation: 11160
What is the best way to repeat the elements of an array according to the corresponding numbers in another array? For example, given:
import numpy as np
a = np.array([100,50,200,10])
b = np.array([0.5,0.1,0.15,0.25])
How can I have an array c
that includes numbers from b
repeated according to the numbers in a
:
c = [0.5, 0.5, ..., 0.5, 0.1, 0.1, ... 0.1, 0.15, ..., 0.15, 0.25, ..., 0.25]
where the counts of 0.5, 0.1, 0.15 and 0.25 are respectively 100, 50, 200, and 10.
I know I can do it by using a for loop along with np.repeat
and packing results in an array. But is there a better way in numpy to do this?
Upvotes: 0
Views: 820
Reputation: 4051
import numpy as np
a = np.array([100,50,200,10])
b = np.array([0.5,0.1,0.15,0.25])
c = np.repeat(b,a)
Upvotes: 1