Python 熊猫系列中的真假条纹
我正在努力研究如何在熊猫系列中显示Python 熊猫系列中的真假条纹,python,pandas,boolean,series,cumsum,Python,Pandas,Boolean,Series,Cumsum,我正在努力研究如何在熊猫系列中显示True或False的条纹 数据: 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值,以显示我
True
或False
的条纹
数据:
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
值,以显示我的所需输出,如下所示:
0 0
1 0
2 0
3 1
4 2
5 3
6 0
7 1
8 0
如果p
不等于edp
并且:
感谢您提供另一个解决方案:
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
另一种替代解决方案是创建
p
系列的累积和,并减去p
为0
的最近累积和。然后倒转p
并执行同样的操作。最后多个系列
一起:
c = p.cumsum()
a = c.sub(c.mask(p).ffill(), fill_value=0).sub(1).abs()
c = (~p).cumsum()
d = c.sub(c.mask(~(p)).ffill(), fill_value=0).sub(1).abs()
print (a)
0 0.0
1 1.0
2 0.0
3 1.0
4 2.0
5 3.0
6 1.0
7 1.0
8 0.0
dtype: float64
print (d)
0 1.0
1 0.0
2 1.0
3 1.0
4 1.0
5 1.0
6 0.0
7 1.0
8 1.0
dtype: float64
c = p.cumsum()
a = c.sub(c.mask(p).ffill(), fill_value=0).sub(1).abs()
c = (~p).cumsum()
d = c.sub(c.mask(~(p)).ffill(), fill_value=0).sub(1).abs()
print (a)
0 0.0
1 1.0
2 0.0
3 1.0
4 2.0
5 3.0
6 1.0
7 1.0
8 0.0
dtype: float64
print (d)
0 1.0
1 0.0
2 1.0
3 1.0
4 1.0
5 1.0
6 0.0
7 1.0
8 1.0
dtype: float64
print (a.mul(d).astype(int))
0 0
1 0
2 0
3 1
4 2
5 3
6 0
7 1
8 0
dtype: int32