Apply boolean mask with datetime to extract specific month with a Pandas dataframe

Question:

I have a dataframe with a column ["DATE"].

I converted the column as a datetime object with :

df["DATE"] = pd.to_datetime(df["DATE"])

Now I want to extract only june month with a boolean mask, but I have an error :

df["DATE"].loc[ df["DATE"] == (datetime.strftime(df["DATE"], "%m") == "06") ]

The error :

descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'

Do you have any idea ? Is the boolean mask syntax wrong or am I missing something ?

I’ve looked this similar question in Stackoverflow but it does not help me because it’s not about boolean mask but multiple steps.

Asked By: Geoffrey

||

Answers:

Use Series.dt.month:

df["DATE"] = pd.to_datetime(df["DATE"])
df[df["DATE"].dt.month == 6]

Your solution working with Series.dt.strftime:

df["DATE"] = pd.to_datetime(df["DATE"])
df[df["DATE"].dt.strftime('%m') == '06']
Answered By: jezrael
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.