【问题标题】:Fill values in numpy array that are between a certain value填充numpy数组中某个值之间的值
【发布时间】:2020-02-04 00:58:40
【问题描述】:

假设我有一个如下所示的数组:

a = np.array([0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0])

我想用 1 填充 1 之间的值。 所以这将是所需的输出:

a = np.array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0])

我查看了this 的答案,结果如下:

array([0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
   1, 1]) 

我确信这个答案非常接近我想要的输出。但是,尽管尝试了无数次,但我无法更改此代码以使其按我想要的方式工作,因为我对 numpy 数组并不精通。 非常感谢任何帮助!

【问题讨论】:

    标签: numpy numpy-ndarray


    【解决方案1】:

    试试这个

    b = ((a == 1).cumsum() % 2) | a
    
    Out[10]:
    array([0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0], dtype=int32)
    

    来自@Paul Panzer:使用ufunc.accumulatebitwise_xor

    b = np.bitwise_xor.accumulate(a)|a
    

    【讨论】:

    • 同样的想法,但速度更快:np.bitwise_xor.accumulate(a)|a.
    • @PaulPanzer:在bitwise_xor 上使用ufunc.accumulate 非常好。我将其添加到答案中
    【解决方案2】:

    试试这个:

    import numpy as np
    
    num_lst = np.array(
    [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0])
    
    i = 0
    while i < len(num_lst): # Iterate through the list
        if num_lst[i]: # Check if element is 1 at i-th position
            if not num_lst[i+1]: # Check if next element is 0
                num_lst[i+1] = 1 # Change next element to 1
                i += 1 # Continue through loop
            else: # Check if next element is 1
                i += 2 # Skip next element
        else:
            i += 1 # Continue through loop
    
    
    print(num_lst)
    

    这可能不是最优雅的执行方式,但它应该可以工作。基本上,我们遍历列表以找到任何 1。当我们找到一个为 1 的元素时,我们检查下一个元素是否为 0。如果是,那么我们将下一个元素更改为 1。如果下一个元素为 1,这意味着我们应该停止将 0s 更改为 1s,所以我们跳过该元素并继续迭代。

    【讨论】:

    • 如果使用 numba 包裹,您可以大大加快解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2017-08-15
    • 2013-12-29
    • 2018-06-23
    相关资源
    最近更新 更多