python - How can I combine datetime.date and datetime.time columns in pandas dataframe? -
given df
date time data 3 2017-08-10 15:15:00 0 2017-08-11 15:15:00 b 1 2017-08-12 15:15:00 c 2 2017-08-13 15:15:00 d 1 2017-08-14 15:15:00 e
and
print (type(df['date'].iat[0])) <class 'datetime.date'> print (type(df['time'].iat[0])) <class 'datetime.time'>
how can combine df.date , df.time datetime column datetime object ??:
date time data datetime 3 2017-08-10 15:15:00 2017-08-10 15:15:00 0 2017-08-11 15:15:00 b 2017-08-11 15:15:00 1 2017-08-12 15:15:00 c 2017-08-12 15:15:00 2 2017-08-13 15:15:00 d 2017-08-13 15:15:00 1 2017-08-14 15:15:00 e 2017-08-14 15:15:00
what tried:
df['datetime'] = df.apply(lambda r : pd.datetime.combine(r['date'],r['time']),1)
this works intended, however, prefer vectorized operation , following msg:
c:\users\user\anaconda3\lib\site-packages\ipykernel\__main__.py:1: settingwithcopywarning: value trying set on copy of slice dataframe. try using .loc[row_indexer,col_indexer] = value instead see caveats in documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy if __name__ == '__main__':
the issue here both date , time in datetime format. try
df['datetime'] = pd.to_datetime(df['date'].dt.strftime('%y-%m-%d') + df['time'].astype(str), format = '%y-%m-%d%h:%m:%s')
though don't know if more efficient using datetime.combine
Comments
Post a Comment