计算 pandas 中连续1个的组 [英] Count groups of consecutive 1s in pandas
本文介绍了计算 pandas 中连续1个的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个"1"和"0"的列表,我想计算连续的"1"的组数.
I have a list of '1's and '0s' and I would like to calculate the number of groups of consecutive '1's.
mylist = [0,0,1,1,0,1,1,1,1,0,1,0]
手工做给我们3个小组,但是有办法用python做吗?
Doing it by hand gives us 3 groups but is there a way to do it by python?
推荐答案
选项1
使用pandas
.首先,初始化一个数据框:
With pandas
. First, initialise a dataframe:
In [78]: df
Out[78]:
Col1
0 0
1 0
2 1
3 1
4 0
5 1
6 1
7 1
8 1
9 0
10 1
11 0
现在按组数计算总数:
In [79]: df.sum() / df.diff().eq(1).cumsum().max()
Out[79]:
Col1 2.333333
dtype: float64
如果只需要组数,那么df.diff().eq(1).cumsum().max()
就足够了.
If you want just the number of groups, df.diff().eq(1).cumsum().max()
is enough.
选项2
使用itertools.groupby
:
In [88]: sum(array) / sum(1 if sum(g) else 0 for _, g in itertools.groupby(array))
Out[88]: 2.3333333333333335
如果只需要组数,那么sum(1 if sum(g) else 0 for _, g in itertools.groupby(array))
就足够了.
If you want just the number of groups, sum(1 if sum(g) else 0 for _, g in itertools.groupby(array))
is enough.
这篇关于计算 pandas 中连续1个的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文