Skip to content
Advertisement

Identify and count segments between a start and an end marker

The goal is to fill values only between two values (start and end) with unique numbers (will be used in a groupby later on), notice how the values between end and start are still None in the desired output:

enter image description here

Code:

JavaScript

Advertisement

Answer

Usually problems like these are solved by fiddling with cumsum and shift.

The main idea for this solution is to identify rows where the number of “starts” seen is ahead of the number of “ends” seen by one.

The only assumption I made is that 'start' and 'end' alternate, beginning with a 'start'.

JavaScript

Visualization:

JavaScript

edit: added .fillna(0) to account for dataframes where the first value in the 'flag' column is 'start'.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement