简体   繁体   English

从pandas Dataframe中提取月份数据

[英]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. 我将它们转换为pandas datetime对象。

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. 这可以返回正确的值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. pandas.Series.dt.month用于转换由datetimes填充的Series和用于转换标量的pandas.Timestamp For converting Index is function pandas.DatetimeIndex.month , there is no .dt . 对于转换Index是函数pandas.DatetimeIndex.month ,没有.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[0]["Date"]返回一个标量: pd.Timestamp对象具有month属性,这是您正在访问的属性。

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. df.loc[1:2]["Date"]返回一个系列: pd.Series对象没有 month属性,如果df['Date']是一个datetime系列,它们确实有一个dt.month属性。

In addition, don't use chained indexing . 另外, 不要使用链式索引 You can use: 您可以使用:

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

df.loc[1:2, 'Date'].dt.month for a series df.loc[1:2, 'Date'].dt.month为一个系列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM