大 pandas 系列中对错的条纹 [英] Streaks of True or False in pandas Series

查看:51
本文介绍了大 pandas 系列中对错的条纹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何在熊猫系列中显示 True False 的条纹.

I'm trying to work out how to show streaks of True or False in a pandas Series.

数据:

p = pd.Series([True,False,True,True,True,True,False,False,True])

0     True
1    False
2     True
3     True
4     True
5     True
6    False
7    False
8     True
dtype: bool

我尝试了 p.diff(),但不确定如何计算生成的 False 值,以显示我的所需输出,如下所示:如下:

I tried p.diff() but not sure how to count the False values this generates to show my desired output which is as follows:.

0     0
1     0
2     0
3     1
4     2
5     3
6     0
7     1
8     0

推荐答案

您可以使用 cumsum :

You can use cumcount of consecutives groups created by compare if p is not equal with shifted p and cumsum:

print (p.ne(p.shift()))
0     True
1     True
2     True
3    False
4    False
5    False
6     True
7    False
8     True
dtype: bool

print (p.ne(p.shift()).cumsum())
0    1
1    2
2    3
3    3
4    3
5    3
6    4
7    4
8    5
dtype: int32

print (p.groupby(p.ne(p.shift()).cumsum()).cumcount())
0    0
1    0
2    0
3    1
4    2
5    3
6    0
7    1
8    0
dtype: int64

谢谢 MaxU 另一种解决方案:

print (p.groupby(p.diff().cumsum()).cumcount())
0    0
1    0
2    0
3    1
4    2
5    3
6    0
7    1
8    0
dtype: int64 

这篇关于大 pandas 系列中对错的条纹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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