I have a df where I would like to filter for multiple years Pandas
Data
id type stat date
aa ss y 2022-01-01
bb tt y 2023-01-05
cc uu n 2023-01-05
aa hi y 2021-01-01
aa hi n 2021-02-01
Desired
id type stat date
aa ss y 2022-01-01
bb tt y 2023-01-05
cc uu n 2023-01-05
I wish to retrieve years 2022 and 2023.
Doing
df = df[df['date'].dt.year == 2022 & 2023]
Any suggestion is appreciated
CodePudding user response:
coerce to datetime and filter by dt.year
df[pd.to_datetime(df['date']).dt.year.isin([2022,2023])]
CodePudding user response:
You may also check between
df[df.date.between('2022-01-01','2024-01-01')]
id type stat date
0 aa ss y 2022-01-01
1 bb tt y 2023-01-05
2 cc uu n 2023-01-05
