Skip to content
Advertisement

Update column based on other column condition

I need to update vid or maybe create a new column based on the change column

df = [{'vid': 14, 'change': 0}, {'vid': 15, 'change': 1}, {'vid': 16, 'change': 0}, {'vid': 16, 'change': 0}, {'vid': 17, 'change': 0}, {'vid': 17, 'change': 1}, {'vid': 18, 'change': 0}, {'vid': 18, 'change': 0}]

JavaScript

If change == 1 then the next set of vid should be changed to the current and if change == 0 then the next vid should stay the same.

From my example above vid 16 needs to be changed to 15 since 15 has change = 1 however 17 stays since 16 doesn’t have change = 1

Change = 1 will only occur when vid is going to change in the next row

Expected output

JavaScript

Advertisement

Answer

If you don’t mind renumbering all the replaced numbers to be sequential, you can get a pretty clean version of it by subtracting the shifted cumsum of change:

JavaScript

Another option with the original numbering is to use map and groupby:

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