Home > Mobile >  Generate last friday of each month in pandas
Generate last friday of each month in pandas

Time:03-14

I have looked around certain date_range functions and offset function, but cant really find a quick way to generate the last friday dates of any/each month in any given year. Is there a easy solution please? I have looked around a stack overflow post as well (which use dateutil), but that one does not really seem robust/straightforward

Can you assist please

CodePudding user response:

Use:

#generate all Fridays between start end datetimes
r = pd.date_range('2020-01-01','2022-01-01', freq='W-FRI')
#filter last Friday per month periods
r = r.to_series().groupby(r.to_period('m')).last()

print (r)
2020-01   2020-01-31
2020-02   2020-02-28
2020-03   2020-03-27
2020-04   2020-04-24
2020-05   2020-05-29
2020-06   2020-06-26
2020-07   2020-07-31
2020-08   2020-08-28
2020-09   2020-09-25
2020-10   2020-10-30
2020-11   2020-11-27
2020-12   2020-12-25
2021-01   2021-01-29
2021-02   2021-02-26
2021-03   2021-03-26
2021-04   2021-04-30
2021-05   2021-05-28
2021-06   2021-06-25
2021-07   2021-07-30
2021-08   2021-08-27
2021-09   2021-09-24
2021-10   2021-10-29
2021-11   2021-11-26
2021-12   2021-12-31
Freq: M, dtype: datetime64[ns]

Or create month range and subtract week if no Friday:

a = pd.date_range('2020-01-01','2022-01-01', freq='M')
r = a.where(a.weekday == 4, a - pd.offsets.Week(weekday=4))
print (r)
DatetimeIndex(['2020-01-31', '2020-02-28', '2020-03-27', '2020-04-24',
               '2020-05-29', '2020-06-26', '2020-07-31', '2020-08-28',
               '2020-09-25', '2020-10-30', '2020-11-27', '2020-12-25',
               '2021-01-29', '2021-02-26', '2021-03-26', '2021-04-30',
               '2021-05-28', '2021-06-25', '2021-07-30', '2021-08-27',
               '2021-09-24', '2021-10-29', '2021-11-26', '2021-12-31'],
              dtype='datetime64[ns]', freq=None)
  • Related