Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

python 3.x - How to combine multiple columns in a Data Frame to Pandas datetime format

I have a pandas data frame with values as below

ProcessID1 UserID Date Month Year Time 248 Tony 29 4 2017 23:30:56 436 Jeff 28 4 2017 20:02:19 500 Greg 4 5 2017 11:48:29 I would like to know is there any way I can combine columns of Date,Month&Year & time to a pd.datetimeformat?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use to_datetime with automatic convert column Day,Month,Year with add times converted to_timedelta:

df['Datetime'] = pd.to_datetime(df.rename(columns={'Date':'Day'})[['Day','Month','Year']]) + 
                 pd.to_timedelta(df['Time'])

Another solutions are join all column converted to strings first:

df['Datetime'] = pd.to_datetime(df[['Date','Month','Year', 'Time']]
                   .astype(str).apply(' '.join, 1), format='%d %m %Y %H:%M:%S')
df['Datetime']  = (pd.to_datetime(df['Year'].astype(str) + '-' +
                                  df['Month'].astype(str) + '-' +
                                  df['Date'].astype(str) + ' ' +
                                  df['Time']))

print (df)
   ProcessID1 UserID  Date  Month  Year      Time            Datetime
0         248   Tony    29      4  2017  23:30:56 2017-04-29 23:30:56
1         436   Jeff    28      4  2017  20:02:19 2017-04-28 20:02:19
2         500   Greg     4      5  2017  11:48:29 2017-05-04 11:48:29

Last if need remove these columns:

df = df.drop(['Date','Month','Year', 'Time'], axis=1)
print (df)
   ProcessID1 UserID            Datetime
0         248   Tony 2017-04-29 23:30:56
1         436   Jeff 2017-04-28 20:02:19
2         500   Greg 2017-05-04 11:48:29

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...