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

痞子三分冷 提交于 2019-12-01 04:44:20

问题


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

Anyone has any idea?

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


回答1:


It seems you need 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:

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

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


来源:https://stackoverflow.com/questions/41918115/how-do-i-extract-the-date-year-month-from-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!