简体   繁体   English

如何计算 numpy 数组中元素的特定范围

[英]How to count the particuler range of elements in an numpy array

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.需要统计一个数组的个数,我可以用这个function来统计。

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

the output I got:我得到的 output:

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但是,需要一个特殊要求,例如如果连续超过3次则只计算那些,这种情况下连续超过3次的例外计数为5

expected output:预期 output:

5

A simple method would be to use a "running average" of window-size 3 and then compare to 1 .一个简单的方法是使用窗口大小 3 的“运行平均值”,然后与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:我仍然不明白为什么 OP 使用 2d 数组,但我不会更改示例,而是将其展平:

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

You can erode/dilate your data to remove the stretches of less than N consecutive 1s.您可以侵蚀/扩张您的数据以删除少于 N 个连续 1 的延伸。

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: 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM