Let's assume we want to build a DatetimeIndex
object consisting of all Mondays and Thursdays in 2023. How would one go about doing this using pandas?
Specifically, I have the start and end of a time period and I want to create the following Datetime
object:
pd.date_range(start, end, freq)
The problem I am having is I don't know how to captures the said days of the time period as I am not sure what to put for freq.
CodePudding user response:
Let's use pandas business daterange with weekmask:
pd.bdate_range('2023-01-01', '2023-12-31', freq='C', weekmask='1001000')
Alternatively you can use boolean indexing to filter the required day names:
d = pd.date_range('2023-01-01', '2023-12-31')
d[d.day_name().isin(['Monday', 'Thursday'])]
Result
DatetimeIndex(['2023-01-02', '2023-01-05', '2023-01-09', '2023-01-12',
'2023-01-16', '2023-01-19', '2023-01-23', '2023-01-26',
'2023-01-30', '2023-02-02',
...
'2023-11-27', '2023-11-30', '2023-12-04', '2023-12-07',
'2023-12-11', '2023-12-14', '2023-12-18', '2023-12-21',
'2023-12-25', '2023-12-28'],
dtype='datetime64[ns]', length=104, freq=None)