计算 numpy 数组中连续出现的长度不同的值 [英] Count consecutive occurences of values varying in length in a numpy array
问题描述
假设我在一个 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
使用这个布尔数组,我想计算 True 连续出现的所有长度.例如,如果我有 [True,True,True,False,False,True,True,False,True]
我想找回 [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]
.
我可以使用此代码做到这一点:
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
但是是否已经为此或python、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]
这篇关于计算 numpy 数组中连续出现的长度不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!