Convert datetime string to new columns of Day, Month, Year in pandas data frame

泪湿孤枕 提交于 2019-12-22 09:19:16

问题


I am new to python and have a pretty simple (hopefully straightforward!) question.

Say that I have a data frame with 3 columns: time (which is in the format YYYY-MM-DDTHH:MM:SSZ), device_id, and rain but I need the first column, "time", to become three columns of "day", "month", and "year" with values from the timestamp.

So the original data frame looks something like this:

     time                  device_id                              rain
     2016-12-27T00:00:00Z  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     2016-12-28T00:00:00Z  9b839362-b06d-4217-96f5-f261c1ada8d6   0.2
     2016-12-29T00:00:00Z  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     2016-12-30T00:00:00Z  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     2016-12-31T00:00:00Z  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN

But I'm trying to get the data frame to look like this:

     day  month  year  device_id                              rain
     27   12     2016  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     28   12     2016  9b839362-b06d-4217-96f5-f261c1ada8d6   0.2
     29   12     2016  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     30   12     2016  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN
     31   12     2016  9b839362-b06d-4217-96f5-f261c1ada8d6   NaN

I don't care about the hour/seconds/minutes but need these values from the original time stamp, and I don't even know where to start. Please help!

Here's some reproducible code to get started:

>> import pandas as pd 
>> df = pd.DataFrame([['2016-12-27T00:00:00Z', '9b839362-b06d-4217-96f5-f261c1ada8d6', 'NaN']], columns=['time', 'device_id', 'rain'])
>> print df
2016-12-27T00:00:00Z  9b849362-b06d-4217-96f5-f261c1ada8d6  NaN

回答1:


Just split the time with - or T and the first three elements should correspond to the year, month and day column, concatenate it with the other two columns will get what you need:

pd.concat([df.drop('time', axis = 1), 
          (df.time.str.split("-|T").str[:3].apply(pd.Series)
          .rename(columns={0:'year', 1:'month', 2:'day'}))], axis = 1)


An alternative close to @nlassaux's approach would be:

df['time'] = pd.to_datetime(df['time'])   
df['year'] = df.time.dt.year
df['month'] = df.time.dt.month
df['day'] = df.time.dt.day
df.drop('time', axis=1, inplace=True)



回答2:


The cleanest way is to use builtin pandas datetime functions.

First, convert the column to datetime:

df["time"] = pd.to_datetime(df["time"])

Then, extract your information:

df["day"] = df['time'].map(lambda x: x.day)
df["month"] = df['time'].map(lambda x: x.month)
df["year"] = df['time'].map(lambda x: x.year)


来源:https://stackoverflow.com/questions/41455967/convert-datetime-string-to-new-columns-of-day-month-year-in-pandas-data-frame

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