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'
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.