reverse looping using lambda in pandas

Viewed 41

I have a function

def age_func(row):
  if row["temp_col"] == 0 and set_flag == 0:
    set_flag = 1
  elif if row["temp_col"] == 1 and set_flag == 0:
    ***code**
  else:
    ****code here****

#loops row-wise in the dataframe
df['final_col'] = ts.apply (lambda row: age_func(row), axis=1)

But want to loop through last row to first row for this code to work. Can anyone suggest me Any alternative approach by using lambda so that I can loop in reverse order.

1 Answers

Since it's not clear what exactly your function does, and the question was about the reverse order of processing the rows of the frame, you can reverse the frame with [::-1]. Below is an example.

def age_func(row):
    global counter
    counter += 1
    return f'Processed {counter}th'

ts = pd.DataFrame({'temp_col': [1, 0, 1, 0, 1, 0], 'order': [0, 1, 2, 3, 4, 5]})
counter = -1

# loops row-wise in the dataframe
ts['final_col'] = ts[::-1].apply(lambda row: age_func(row), axis=1)
print(ts)
   temp_col  order      final_col
0         1      0  Processed 5th
1         0      1  Processed 4th
2         1      2  Processed 3th
3         0      3  Processed 2th
4         1      4  Processed 1th
5         0      5  Processed 0th
Related