Skip to content Skip to sidebar Skip to footer

Fast Way To Select N Items (drawn From A Poisson Distribution) For Each Element In Array X

I am having some trouble with solving a problem I encountered. I have an array with prices: >>> x = np.random.randint(10, size=10) array([6, 1, 7, 6, 9, 0, 8, 2, 1, 8]) A

Solution 1:

You could use np.repeat:

In [43]: x = np.array([6, 1, 7, 6, 9, 0, 8, 2, 1, 8])

In [44]: arrivals = np.array([4, 0, 1, 1, 3, 2, 1, 3, 2, 1])

In [45]: np.repeat(x, arrivals)
Out[45]: array([6, 6, 6, 6, 7, 6, 9, 9, 9, 0, 0, 8, 2, 2, 2, 1, 1, 8])

but note that for certain calculations, it might be possible to avoid having to form this intermediate array. See for example, scipy.stats.binned_statistic.

Solution 2:

I don't really see how you could do that without looping at all. What you could do is create the result array prior to looping; that way you don't need to concatenate afterwards.

Result = np.empty( arrivals.sum(), dtype='i' )

and then change the values of that array blockwise:

Result_position = np.r_[ [0], arrivals.cumsum() ]
fori, xx inenumerate(x):
    Result[ Result_position[i]:Result_position[i+1] ] = xx

Post a Comment for "Fast Way To Select N Items (drawn From A Poisson Distribution) For Each Element In Array X"