I have dataframe like this:

point switch_on
A True
B True
C True
A False
D False
N True
O False
O False
S False

I want to add another column which will determine groups of rows that contain the same boolean before switching. Like this:

point switch_on group
A True 1
B True 1
C True 1
A False 2
D False 2
N True 3
O False 4
O False 4
S False 4

推荐答案

Identify every time there's a change:

  • This is when the current value df.switch_on doesn't equal the previous value df.switch_on.shift().

Then take the cumsum:

  • True is interpreted as 1, and False as 0.
df['group'] = df.switch_on.ne(df.switch_on.shift()).cumsum()
print(df)

Output:

  point  switch_on  group
0     A       True      1
1     B       True      1
2     C       True      1
3     A      False      2
4     D      False      2
5     N       True      3
6     O      False      4
7     O      False      4
8     S      False      4

Python相关问答推荐

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

通过pandas向每个非空单元格添加子字符串

Odoo 16使用NTFS使字段只读

python中的解释会在后台调用函数吗?

无法连接到Keycloat服务器

Python全局变量递归得到不同的结果

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

如何在海上配对图中使某些标记周围的黑色边框

如何使用正则表达式修改toml文件中指定字段中的参数值

如何获得3D点的平移和旋转,给定的点已经旋转?

合并相似列表

高效生成累积式三角矩阵

Pandas ,快速从词典栏中提取信息到新栏

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)

如何在微调Whisper模型时更改数据集?

牛郎星直方图中分类列的设置顺序

Wagail:当通过外键访问索引页时,如何过滤索引页的子项

有理由将基于Django职业的观点个人化吗?

nameError_C未定义

用考克斯回归的生存分析系列的真值是模棱两可的.