ade*_*e1e 5 python boolean series pandas 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
Run Code Online (Sandbox Code Playgroud)
我尝试过p.diff(),但不确定如何计算False生成的值以显示我想要的输出,如下所示:
0 0
1 0
2 0
3 1
4 2
5 3
6 0
7 1
8 0
Run Code Online (Sandbox Code Playgroud)
如果不等于ed和,您可以使用cumcount通过比较创建的连续组:pshiftpcumsum
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
Run Code Online (Sandbox Code Playgroud)
谢谢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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2619 次 |
| 最近记录: |