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

Time:10-24

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.

CodePudding user response:

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']
  • Related