first time here, so I have a data frame that is read from a csv file using Pathlib. It looks something like this
I want to create a new column, called 'Date Check' that verify each date on the date column and return 'True' if a pre-specified condition is met. In this case, return 'True' if the date is the second Monday of every month.
I have no experience with time or datetime library so please explain the code if you are using those.
Thanks !!!
Date | Date Check |
---|---|
2019/01/01 | |
2019/01/02 | |
2019/01/03 | |
2019/01/04 | |
... | |
2021/01/01 | |
2021/01/02 | |
2021/01/03 |
CodePudding user response:
you can make use of dt.day
and dt.weekday
attributes to select Monday and make sure it's the second of the month:
import pandas as pd
df = pd.DataFrame({'Date': pd.date_range('2020-01-01', '2020-01-31', freq='d')})
df['is_second_Monday'] = ((df['Date'].dt.weekday == 0) & # select Monday
(df['Date'].dt.day > 7) & # exclude first
(df['Date'].dt.day <= 14)) # exclude third etc.
print(df['Date'][df['is_second_Monday']])
# 12 2020-01-13
# Name: Date, dtype: datetime64[ns]