如何从 pandas 数据框中提取日期/年/月? [英] How do I extract the date/year/month from pandas dataframe?

查看:307
本文介绍了如何从 pandas 数据框中提取日期/年/月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

有人有什么想法吗?

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

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

推荐答案

似乎您需要 to_datetime

It seems you need to_datetime:

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

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

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

如果需要提取 year mon th 到新列:

If need extract year, month and day to new columns:

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

如果需要列表 date s:

If need list of dates:

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)]

这篇关于如何从 pandas 数据框中提取日期/年/月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆