0

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.

Bella_18
  • 624
  • 1
  • 14
  • 2
    you probably meant `and` instead of `&&` – OrenIshShalom Sep 20 '22 at 16:18
  • 1
    what is ```set_flag``` ? a column name ? – khaled koubaa Sep 20 '22 at 16:22
  • 2
    What are you really trying to compute? This looks like an inefficient method. Please provide a minimal example and explain the logic – mozway Sep 20 '22 at 16:38
  • See [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – BeRT2me Sep 20 '22 at 16:41
  • @mozway. I am trying to generate a column: please check this question. https://stackoverflow.com/questions/73789609/generate-first-and-last-working-day-of-month-from-time-series-data?noredirect=1#comment130297441_73789609 – Bella_18 Sep 20 '22 at 16:54

1 Answers1

1

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
Алексей Р
  • 7,507
  • 2
  • 7
  • 18