d_s_m
d_s_m

Reputation: 67

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?

Upvotes: 4

Views: 1158

Answers (1)

QtRoS
QtRoS

Reputation: 1177

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 ]

Upvotes: 4

Related Questions