计数长度变化值的连续OCCURENCES在numpy的阵列 [英] Count consecutive occurences of values varying in length in a numpy array

查看:301
本文介绍了计数长度变化值的连续OCCURENCES在numpy的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一串数字在numpy的阵列和我进行测试的基础上返回布尔数组的一个条件:

Say I have a bunch of numbers in a numpy array and I test them based on a condition returning a boolean array:

np.random.seed(3456)
a = np.random.rand(8)
condition = a>0.5

和这个布尔数组我要统计所有的真连续OCCURENCES的长度。例如,如果我有 [真,真,真,假,假,真,真,假,真] 我想找回 [ 3,2,1]

And with this boolean array I want to count all of the lengths of consecutive occurences of True. For example if I had [True,True,True,False,False,True,True,False,True] I would want to get back [3,2,1].

我能做到这一点使用此code:

I can do that using this code:

length,count = [],0
for i in range(len(condition)):

    if condition[i]==True:
        count += 1
    elif condition[i]==False and count>0:
        length.append(count)
        count = 0

    if i==len(condition)-1 and count>0:
        length.append(count)

    print length

但有已经为这个或蟒蛇,numpy的,SciPy的实施什么,等功能计数在列表或数组给定输入?

But is there anything already implemented for this or a python,numpy,scipy, etc. function that counts the length of consecutive occurences in a list or array for a given input?

推荐答案

下面是一个使用和itertools(这可能不是最快的解决方案)的解决方案:

Here's a solution using itertools (it's probably not the fastest solution):

import itertools
condition = [True,True,True,False,False,True,True,False,True]
[ sum( 1 for _ in group ) for key, group in itertools.groupby( condition ) if key ]

Out:
[3, 2, 1]

这篇关于计数长度变化值的连续OCCURENCES在numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆