rinks
rinks

Reputation: 21

Increment or reset counter based on an existing value of a data frame column in Pandas

I have a dataframe imported from csv file along the lines of the below:

      Value       Counter 
  1.    5           0
  2.    15          1
  3.    15          2           
  4.    15          3
  5.    10          0
  6.    15          1
  7.    15          1

I want to increment the value of counter only if the value= 15 else reset it to 0. I tried cumsum but stuck how to reset it back to zero of nonmatch

Here is my code

     import pandas as pd
     import csv
     import numpy as np
     dfs = []
     df = pd.read_csv("H:/test/test.csv")
     df["Counted"] = (df["Value"] == 15).cumsum()
     dfs.append(df)
     big_frame = pd.concat(dfs, sort=True, ignore_index=False)
     big_frame.to_csv('H:/test/List.csv' , index=False)

Thanks for your help

Upvotes: 2

Views: 245

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150805

Here's my approach:

s = df.Value.ne(15)
df['Counter'] = (~s).groupby(s.cumsum()).cumsum()

Upvotes: 2

Related Questions