[英]How do I extract the date/year/month from pandas dataframe?
I'm trying to extract year/date/month info from the 'date' column in pandas dataframe. 我正在尝试从pandas数据框中的“日期”列中提取年/日期/月信息。 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
Anyone has any idea? 有人知道吗?
Btw, this is the dataframe I use (calendar_data): 顺便说一句,这是我使用的数据框(calendar_data):
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
, month
and day
to new columns: 如果需要将year
, month
和day
提取到新列中:
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
If need list
of date
s: 如果需要date
list
:
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.