I am trying to iterate through a DataFrame, and when the value changes, increment the counter, and then set a new column equal to that value. I can get this to work with a global counter, for example:
def change_ind(row):
global prev_row
global k
if row['rep'] != prev_row:
k = k+1
prev_row = row['rep']
return k
But when I try to pass the arguments to the apply function as shown below, it no longer works. It seems that it resets the values of k, prev_row every time it runs on a new line. Is there a way to pass arguments to a function and get the result I'm looking for? Or is the best way to do this at all?
def change_ind(row, k, prev_row):
if row != prev_row:
k = k+1
prev_row = row
return k
source
share