Python 如何从熊猫数据框中提取日期/年/月?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41918115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:52:08  来源:igfitidea点击:

How do I extract the date/year/month from pandas dataframe?

pythonpandasdataframedata-science

提问by Zhenyu Bo

I'm trying to extract year/date/month info from the 'date' column in pandas dataframe. Here is my sample code:

我正在尝试从 Pandas 数据框中的“日期”列中提取年/日/月信息。这是我的示例代码:

from datetime import datetime
def date_split(calendar):
  for row in calendar: 
    new_calendar={}
    listdate=datetime.strptime(row['date'],'%Y-%M-%D')

I haven't finished the complete code, but when i test run this part I keep getting error like this:

我还没有完成完整的代码,但是当我测试运行这部分时,我不断收到这样的错误:

----> 7         listdate=datetime.strptime(row['date'],'%Y-%M-%D')
TypeError: string indices must be integers

Anyone has any idea?

任何人有任何想法?

Btw, this is the dataframe I use (calendar_data):

顺便说一句,这是我使用的数据框(calendar_data):

enter image description here

在此处输入图片说明

回答by jezrael

It seems you need to_datetime:

看来你需要to_datetime

print (df['date'].dtype)
object

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

print (df['date'].dtype)
datetime64[ns]

If need extract year, monthand dayto new columns:

如果需要提取yearmonthday到新列:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day

If need listof dates:

如果需要listdateS:

listdate = df['date'].dt.date.tolist()
print (listdate)

[datetime.date(2017, 9, 5), 
 datetime.date(2017, 9, 4),
 datetime.date(2017, 9, 3), 
 datetime.date(2017, 9, 2),
 datetime.date(2017, 9, 1)]