Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the last week of each month only from a data frame - Python/Pandas

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?

like image 930
d_s_m Avatar asked Oct 23 '25 12:10

d_s_m


1 Answers

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 ]
like image 110
QtRoS Avatar answered Oct 25 '25 01:10

QtRoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!