Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract month data from pandas Dataframe

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'
like image 557
Bazman Avatar asked Jan 02 '23 14:01

Bazman


1 Answers

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

like image 185
jpp Avatar answered Jan 05 '23 15:01

jpp