Merge Pandas DateTime DataFrame Columns

Suppose I have dataframes as shown below:

Year Month Day 2003 1 8 2003 2 7 

How to combine Year, Month and Day in a newly defined column in the data frame as such, the dataframe will be as follows:

 Year Month Day Date 2003 1 8 2003-1-8 2003 2 7 2003-2-7 

Any idea on this?

I am using pandas python dataframe

Thanks!

+8
python pandas dataframe
source share
2 answers
 >>> from datetime import datetime >>> df['Date'] = df.apply(lambda row: datetime( row['Year'], row['Month'], row['Day']), axis=1) >>> df Year Month Day Date 0 2003 1 8 2003-01-08 00:00:00 1 2003 2 7 2003-02-07 00:00:00 
+15
source share

Better use pd.to_datetime :

 df['Date'] = pd.to_datetime(df[['Year','Month','Day']]) >>> df Year Month Day Date 0 2003 1 8 2003-01-08 1 2003 2 7 2003-02-07 
0
source share

All Articles