简体   繁体   中英

How to repeat specific elements in numpy array?

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

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]

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

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM