Skip to content
Advertisement

Pandas: add column with progressive count of elements meeting a condition

Given the following dataframe df:

JavaScript

I want to add another column that counts, progressively, the elements with df['B']='yes':

JavaScript

How can I do this?

Advertisement

Answer

You can use numpy.where with cumsum of boolean mask:

JavaScript

Another solution is count boolean mask created by filtering and then add 0 values by reindex:

JavaScript

Performance (in real data should be different, best check it first):

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