Helly Bhalodia
Helly Bhalodia

Reputation: 31

increment counter in a column based on certain condition pandas

col1     col2
 -        -
 -        -
 no       1
 -        -
 no       2
 no       3

I have 2 columns in a dataframe. Whenever 'no' is encountered in col1, need to increment the counter in col2 as shown above

Upvotes: 2

Views: 849

Answers (1)

jezrael
jezrael

Reputation: 862406

Campare values by Series.eq for ==, then use cumulative sum and replace non no values to - by Series.where:

m = df['col1'].eq('no')
df['col2'] = m.cumsum().where(m, '-')
print (df)
  col1 col2
0    -    -
1    -    -
2   no    1
3    -    -
4   no    2
5   no    3

Upvotes: 3

Related Questions