I have a column called "date" that has data for every day of the year and I want to get only the row that corresponds to the last day of the month, how can I do that?
Asked
Active
Viewed 579 times
-1
-
1Does this answer your question? [How to get the last day of the month?](https://stackoverflow.com/questions/42950/how-to-get-the-last-day-of-the-month) – David Buck Jan 27 '22 at 21:16
-
1You don't say so, but I assume you're using Pandas? If so, you should [edit] your question to add the pandas tag - although the answer linked above should solve your problem. – David Buck Jan 27 '22 at 21:18
-
I have a column called "date" that has data for every day of the year. I want to select only the row that corresponds to the last day of each month. Somebody can tell me how can I do that, please? – Txucambiro Jan 27 '22 at 23:25
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 06 '22 at 08:59
1 Answers
0
Assuming you're using pandas, you can use the datetime package to check this.
Since some months have differents amounts of days, I'm using it to check the date of the next day, if the next date have a day equal to 1, then the day we are at is the last of that month.
from datetime import date, timedelta
import pandas
def check_last_month_day(day):
next_day = date.fromisoformat(day) + timedelta(days=1)
return next_day.day == 1
That function receives a string in the date format, creates an date object from that string and then adds one day in the date. After doing this, it just returns a boolean that checks if the day of the next date is equal to 1. for example:
>>> check_last_month_day('2020-01-30')
False
>>> check_last_month_day('2020-01-31')
True
So, now you can filter the dataframe rows using this function: (assuming you named your dataframe as df)
df_filtered = df[ df['date'].apply(check_last_month_day) ]

rgportacio
- 11
- 2