How to convert datetime.time columns in dataframe to string

浪尽此生 提交于 2021-02-11 04:59:58

问题


I've been struggling to convert two columns in a pandas. The frame contains many columns, and 2 columns with dates: 'datelog'(is a date) and 'Timeofday' (is a time). The column datelog is a string. The column Timeofday is a datetime.time() format. The dateframe display is as folows:

     datelog Timeofday
0  30-APR-15  14:15:43
1  30-APR-15  14:16:13
2  30-APR-15  14:16:43
3  30-APR-15  14:17:13
4  30-APR-15  14:17:43
5  30-APR-15  14:18:13
6  30-APR-15  14:18:43
7  30-APR-15  14:19:13
8  30-APR-15  14:19:43
9  30-APR-15  14:20:13

My goal is to concatenate these two column to use them as a index for a timeseries. Can somebody point me in the right direction?


回答1:


I think you can use something like this to create your index:

df.index = df['datelog'] + ' ' + df['Timeofday'].astype(str)



回答2:


You can use to_datetime and to_timedelta if want DatetimeIndex. If not, use ysearka solution:

df.index = pd.to_datetime(df.datelog) + pd.to_timedelta(df.Timeofday)

print (df.index)
DatetimeIndex(['2015-04-30 14:15:43', '2015-04-30 14:16:13',
               '2015-04-30 14:16:43', '2015-04-30 14:17:13',
               '2015-04-30 14:17:43', '2015-04-30 14:18:13',
               '2015-04-30 14:18:43', '2015-04-30 14:19:13',
               '2015-04-30 14:19:43', '2015-04-30 14:20:13'],
              dtype='datetime64[ns]', freq=None)


来源:https://stackoverflow.com/questions/38098015/how-to-convert-datetime-time-columns-in-dataframe-to-string

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