在numpython数组中计算连续数

2024-10-02 02:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

努比的新朋友。我有一个由1和0组成的二维数组,我正试图对角扫描一个特定长度的连续1。找到模式后,函数应返回模式开始的索引,即拉伸中第一个“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

谢谢


Tags: inforindexifmatchcount模式ones
1条回答
网友
1楼 · 发布于 2024-10-02 02:34:51

我觉得你太复杂了,不如:

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

相关问题 更多 >

    热门问题