Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write to the last occurrence of loc?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading