If I have a data frame that is indexed by weekly dates (2019-01-07, 2019-01-14, 2019-01-21...etc), is there a way in Pandas to efficiently select only the rows that correspond to the last week of each month in the index?
Asked
Active
Viewed 1,007 times
1 Answers
4
Just get last day of month (MonthEnd
), then filter, for example (assuming that you have Date
column in your DataFrame
):
from pandas.tseries.offsets import MonthEnd
df['MonthEnd'] = df['Date'] + MonthEnd(1)
df[ (df['MonthEnd'] - df['Date']).dt.days <= 7 ]

QtRoS
- 1,149
- 1
- 16
- 23
-
1I believe it should it should be .dt.days instead of .days, but very helpful nonetheless - thank you! – d_s_m Apr 06 '20 at 21:32
-
@DalvirMandara you are welcome! Indeed it is, I wrote that code by memory :) – QtRoS Apr 07 '20 at 13:03