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]
.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With