Skip to content
Advertisement

Add column with a specific sequence of numbers depending on value

I have this dataframe:

JavaScript
JavaScript

I want to add a new column Sequence with a sequence of numbers. The condition is when the first True appears in the Condition column, the following rows must contain the sequence 1, 2, 3, 1, 2, 3… until another True appears again, at which point the sequence is restarted again. Furthermore, ideally, until the first True appears, the values in the new column should be 0. El resultado final sería:

JavaScript

I have tried to do it with cumsum and cumcount but I can’t find the exact code.

Any suggestion?

Advertisement

Answer

Let us do cumsum to identify blocks of rows, then group the dataframe by blocks and use cumcount to create sequential counter, then with some simple maths we can get the output

JavaScript

Explained

Identify blocks/groups of rows using cumsum

JavaScript

Group the dataframe by the blocks and use cumcount to create a sequential counter per block

JavaScript

Modulo(%) divide the sequential counter by 3 to create a repeating sequence that repeats every three rows

JavaScript

Mask the values in sequence with 0 where the group(b) is < 1

JavaScript

Result

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