【问题标题】:counting consecutive ones in numpy array python在numpy数组python中计算连续的
【发布时间】:2020-06-15 22:31:58
【问题描述】:

numpy 的新手。我有一个由 1 和 0 组成的二维数组,我试图对角扫描一定长度的连续数组。一旦找到模式,该函数应该返回模式开始的索引,即第一个“1”在拉伸中的位置。 这是我最好的尝试:

def find_pattern(array2D, patternlength):
ones_count = 0
pattern_location = []
diag = [array2D.diagonal(i) for i in range(array2D.shape[1]-1,-array2D.shape[0],-1)]
for index, match in np.ndenumerate(diag):
    if match == 1:
        ones_count +=1
    else:
        ones_count == 0
    if ones_count == patternlength:
        pattern_location.append(index)
return pattern_location

但是,当尝试运行时会产生 ValueError:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我理解为什么会出现错误,但我不知道如何解决它。 any() 或 all() 似乎不适合我正在寻找一段连续的情况。

我正在寻找一种不涉及使用额外包(如 pandas 和 itertools)的解决方案。

谢谢!

【问题讨论】:

    标签: python numpy python-3.7


    【解决方案1】:

    我认为你过于复杂了,怎么样:

    import numpy as np
    
    def find_pattern(array2D, patternlength):
        res=[]
        for k in range(-array2D.shape[0]+1, array2D.shape[1]):
            diag=np.diag(array2D, k=k)
            if(len(diag)>=patternlength):
                for i in range(len(diag)-patternlength+1):
                    if(all(diag[i:i+patternlength]==1)):
                        res.append((i+abs(k), i) if k<0 else (i, i+abs(k)))
        return res
    

    示例输入:

    test=np.random.choice([0,1], (12, 14))
    
    print(test)
    
    print(find_pattern(test,3))
    

    返回:

    [[1 1 1 0 0 0 1 0 1 1 1 0 1 1]
     [1 1 0 0 0 1 1 1 1 0 1 0 0 1]
     [1 0 1 1 1 0 1 0 1 1 1 0 0 1]
     [1 1 0 1 0 1 1 0 0 0 1 0 0 0]
     [0 1 0 1 0 1 1 0 1 0 0 0 1 1]
     [1 1 0 0 0 1 0 1 0 1 0 1 0 0]
     [1 0 1 0 0 0 1 1 0 1 1 1 1 1]
     [1 1 1 1 1 1 0 0 0 0 0 0 0 0]
     [1 0 1 1 1 0 1 0 0 0 0 0 0 1]
     [1 0 1 0 0 1 1 1 1 1 0 1 0 0]
     [0 0 1 0 0 1 0 0 1 1 0 1 1 0]
     [0 0 0 0 0 1 1 0 1 1 0 0 0 0]]
    
    [(6, 0), (5, 1), (6, 2), (7, 3), (7, 5), (8, 6), (9, 7), (0, 0), (1, 1), (2, 4), (3, 5), (4, 8), (0, 6), (1, 8)]
    

    【讨论】:

    • 我确实倾向于使事情过于复杂 :) 但是我应该指定我正在寻找的序列不一定在主对角线上,并且可以在数组中的任何位置(对角线) .
    • 干杯,我调整了我的答案 - 这应该对你有用!
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2019-11-14
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多