How to write to the last occurrence of loc?

Question:

I have a dataFrame with date column, and sometimes the date might appear twice.
When I write to a certain date, I would like to write to the last row that have this date, not the first.

Right now I use:

df.loc[df['date'] == date, columnA] =  value

Which in the case of a df like this will write at index 1, not 2:

  date       columnA
0 17.4.2022
1 17.5.2022
2 17.5.2022  value             #in the case of 17.5 write the data to this row.
3 17.6.2022

How to make sure I am writing to the last date all the time, and if there is one, so write into that one?

Asked By: gotiredofcoding

||

Answers:

You can chain mask for last duplicated date value by Series.duplicated:

print (df)
        date  columnA
0  17.4.2022        8
1  17.5.2022        1
2  17.5.2022        1
2  17.5.2022        1
3  17.6.2022        3

date = '17.5.2022'
df.loc[(df['date'] == date) & ~df['date'].duplicated(keep='last'), 'columnA'] =  100

print (df)
        date  columnA
0  17.4.2022        8
1  17.5.2022        1
2  17.5.2022        1
2  17.5.2022      100
3  17.6.2022        3
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.