Here I have a dataframe named all_data. It has a column named 'Order Date', which is of the format datetime. I want to create a new dataframe named 'aug4', which contains all the rows from the 'all_data' dataframe having the date August 4 (year is 2019 for all entries). How do I go about doing the same?
I tried doing
aug4 = all_data.loc[all_data['Order Date'].year == 2019 & all_data['Order Date'].month == 8 & all_data['Order Date'].day == 4]
But it does not work.
Please suggest a solution.
CodePudding user response:
First convert date column to datetime:
all_data['Order Date'] = pd.to_datetime(all_data['Order Date'])
Then wrap your conditions inside () brackets and get year, month and day using dt accessor:
aug4 = all_data.loc[(all_data['Order Date'].dt.year == 2019) & (all_data['Order Date'].dt.month == 8) & (all_data['Order Date'].dt.day == 4)]
CodePudding user response:
You can get Date
from DateTime
and check with Date
like below:
>>> all_data[all_data['Order Date'].dt.date == pd.to_datetime('2019-08-29')]
OR you can convert DateTime
to str
and check with Date
as str:
>>> all_data[all_data['Order Date'].dt.date.astype(str) == '2019-08-29']