Search code examples
pythonpandasdatetime

How to generate a list with every monday, between two dates, and exclude that some a specific list using pandas


I want to generate a dataframe with pandas where one of the columns is filled with all mondays between to dates. But I need to exclude some mondays that are in a specific list. I could generate the column with the mondays, but I could find how to remove that mondays in the given list.

I generate the mondays using:

import pandas as pd

st=pd.to_datetime('8/22/2022') ed=pd.to_datetime('12/22/2022')

a1=pd.date_range(start=st,end=ed, freq='W-MON')

But I would like to exclude the mondays that are in this list

fer=pd.to_datetime(['09/07/2022','10/12/2022','10/15/2022','10/28/2022','11/01/2022','11/14/2022','11/15/2022','11/20/2022'])

I was not able to find the solution online.


Solution

  • IIUC, you can use a negative pandas.Index.isin :

    a1= a1[~a1.isin(fer)]
    

    # Output :

    print(a1)
    ​
    DatetimeIndex(['2022-08-22', '2022-08-29', '2022-09-05', '2022-09-12',
                   '2022-09-19', '2022-09-26', '2022-10-03', '2022-10-10',
                   '2022-10-17', '2022-10-24', '2022-10-31', '2022-11-07',
                   '2022-11-21', '2022-11-28', '2022-12-05', '2022-12-12',
                   '2022-12-19'],
                  dtype='datetime64[ns]', freq=None)