1

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.

Geoffrey
  • 27
  • 4

1 Answers1

1

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']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • As simple as that !!! Many thanks !!!!! – Geoffrey Oct 24 '22 at 08:50
  • For the second solution you added with series.dt.strftime, I still have an error : 'Can only use .dt accessor with datetimelike values. But the first solution works fine ! :) – Geoffrey Oct 24 '22 at 09:02
  • @Geoffrey - hmm, do you add `df["DATE"] = pd.to_datetime(df["DATE"])` before `df[df["DATE"].dt.strftime('%m') == '06']` ? – jezrael Oct 24 '22 at 09:04
  • Hehehe ! You're right, I did not. I tried with ```df["DATE"] = pd.to_datetime(df["DATE"])``` and the second solution worked fine too. Many thanks ! – Geoffrey Oct 24 '22 at 09:09