Home > Blockchain >  How to count the particuler range of elements in an numpy array
How to count the particuler range of elements in an numpy array

Time:09-05

I have an array like:

import numpy as np

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

Requirement:

Needs to count the number of ones in an array, I can count by using this function.

print(np.count_nonzero(data==1))

the output I got:

11

But, one special requirement is needed, like if consecutive ones are more than 3 times then only count the ones, in that case, the excepted count of number ones more than 3 consecutive are 5

expected output:

5

CodePudding user response:

You can erode/dilate your data to remove the stretches of less than N consecutive 1s.

from scipy.ndimage import binary_erosion, binary_dilation

N = 3
k = np.ones((1, N 1))

binary_dilation(binary_erosion(data, k), k).sum()

Output: 5

Output on data=np.array([[0,0,0,1,1,1,0,0,0,0,1,1,1,1,1], [0,0,0,1,1,1,1,1,1,1,1,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]]): 13

CodePudding user response:

A simple method would be to use a "running average" of window-size 3 and then compare to 1.
I still don't understand why the OP is using a 2d array, but instead of changing the example I'll just flatten it out:

import numpy as np

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

def running_avg(x, N):
    return np.convolve(x, np.ones(N)/N, mode='valid')

print(sum(running_avg(data.flatten(), 3) == 1))
# 4, which is actually the correct answer for the given example data as far as I can tell
  • Related