4

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].

4 Answers 4

3

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))
Sign up to request clarification or add additional context in comments.

Comments

2

Using itertools,

a = [1,2,3,4,5]
n = 2

# this can be any condition. E.g., even only
cond = lambda x: x % 2 == 0

b = list(itertools.chain.from_iterable( \
    (itertools.repeat(x, n) if cond(x) else itertools.repeat(x,1)) \
    for x in a))
b
# [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

(The awkward repeat(x,1) is to allow use of chain and avoid having to flatten an array of mixed integers and generators...)

Comments

1

Below would do what you are looking for -

import numpy as np
a = np.asarray([1,2,3,4,5])

n = int(input("Enter value of n "))

new_array = []

for i in range(0,len(a)):
    counter = np.count_nonzero(a == a[i])
    if a[i]%2 != 0:
        new_array.append(a[i])
    elif a[i]>0 and a[i]%2 == 0:
        for j in np.arange(1,n+1):
            new_array.append(a[i])

Comments

1

Try a simple for-loop:

>>> a = [1,2,3,4,5]
>>> new_a = []
>>> n = 2
>>> 
>>> for num in a:
...     new_a.append(num)
...     if num % 2 == 0:
...         for i in range(n-1):
...             new_a.append(num)
... 
>>> new_a
[1, 2, 2, 3, 4, 4, 5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.