如何在numpy数组中重复特定元素?

3

我有一个数组a,如果数组中的元素为偶数或正数,则希望将a的元素重复n次。我的意思是只希望重复满足某些条件的元素。

例如,如果a=[1,2,3,4,5]n=2,条件是偶数,则我想要a变成a=[1,2,2,3,4,4,5]

4个回答

2
一个numpy解决方案。使用np.clipnp.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])

或者您可以使用numpy的ndarray.clip而不是np.clip,这样命令会更短。

m = np.repeat(a, (cond * n).clip(min=1))

1
使用 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]

(笨拙的repeat(x,1)是为了允许使用chain并避免需要展平混合整数和生成器的数组...)

1
尝试使用简单的for循环:
>>> 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]

1
下面的代码可以实现您所需的功能 -
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])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接