New to numpy. I have a 2D array composed of ones and zeros which i'm trying to scan diagonally for a certain length of consecutive ones. Once the pattern(s) has been found the function should return the index of the pattern's beginning, ie the location of the first "1" in the stretch. This is my best attempt:
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
However, when trying to run this produces a ValueError:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I understand why the error is being raised but I can't figure out how to go around it. The any() or all() don't seem to be suitable in the instance that i'm looking for a certain stretch of consecutive ones.
I'm looking for a solution which doesn't involve the use of extra packages such as pandas and itertools.
Thanks!