Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat specific elements in numpy array?

Tags:

python

numpy

I have an array a and I would like to repeat the elements of a n times if they are even or if they are positive. I mean I want to repeat only the elements that respect some condition.

If a=[1,2,3,4,5] and n=2 and the condition is even, then I want a to be a=[1,2,2,3,4,4,5].

like image 798
zdm Avatar asked Sep 02 '25 06:09

zdm


1 Answers

a numpy solution. Use np.clip and np.repeat

n = 2
a = np.asarray([1,2,3,4,5])
cond = (a % 2) == 0  #condition is True on even numbers

m = np.repeat(a, np.clip(cond * n, a_min=1, a_max=None))

In [124]: m
Out[124]: array([1, 2, 2, 3, 4, 4, 5])

Or you may use numpy ndarray.clip instead of np.clip for shorter command

m = np.repeat(a, (cond * n).clip(min=1))
like image 51
Andy L. Avatar answered Sep 04 '25 20:09

Andy L.