4

I originally have dates in string format. I want to extract the month as a number from these dates.

df = pd.DataFrame({'Date':['2011/11/2', '2011/12/20', '2011/8/16']})

I convert them to a pandas datetime object.

df['Date'] = pd.to_datetime(df['Date'])

I then want to extract all the months.

When I try:

df.loc[0]["Date"].month

This works returning the correct value of 11.

But when I try to call multiple months it doesn't work?

df.loc[1:2]["Date"].month

AttributeError: 'Series' object has no attribute 'month'
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Bazman
  • 2,058
  • 9
  • 45
  • 65

2 Answers2

5

df.loc[0]["Date"] returns a scalar: pd.Timestamp objects have a month attribute, which is what you are accessing.

df.loc[1:2]["Date"] returns a series: pd.Series objects do not have a month attribute, they do have a dt.month attribute if df['Date'] is a datetime series.

In addition, don't use chained indexing. You can use:

df.loc[0, 'Date'].month for a scalar

df.loc[1:2, 'Date'].dt.month for a series

jpp
  • 159,742
  • 34
  • 281
  • 339
4

There are different functions. pandas.Series.dt.month for converting Series filled by datetimes and pandas.Timestamp for converting scalar. For converting Index is function pandas.DatetimeIndex.month, there is no .dt.

So need:

#Series
df.loc[1:2, "Date"].dt.month

#scalar
df.loc[0, 'Date'].month

#DatetimeIndex
df.set_index('Date').month
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252