无法将日期和时间合并为大熊猫

时间:2018-11-16 06:55:07

标签: python pandas datetime

我想将以下日期和时间列合并为1个date_time列:

casinghourly[['Date','Time']].head()
Out[275]: 
        Date     Time
0 2014-01-01 00:00:00
1 2014-01-01 01:00:00
2 2014-01-01 02:00:00
3 2014-01-01 03:00:00
4 2014-01-01 04:00:00

我使用了以下代码:

casinghourly.loc[:,'Date_Time'] = pd.to_datetime(casinghourly.Date.astype(str)+' '+casinghourly.Time.astype(str))

但是出现以下错误:

ValueError: Unknown string format

Fyi:

casinghourly[['Date','Time']].dtypes
Out[276]: 
Date     datetime64[ns]
Time    timedelta64[ns]
dtype: object

有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您可以直接将datetime64[ns]timedelta64[ns]连在一起:

df['Date'] = df['Date']+df['Time']

print(df['Date'])
0   2014-01-01 00:00:00
1   2014-01-01 01:00:00
2   2014-01-01 02:00:00
3   2014-01-01 03:00:00
4   2014-01-01 04:00:00
Name: Date, dtype: datetime64[ns]

print(df)
                 Date     Time
0 2014-01-01 00:00:00 00:00:00
1 2014-01-01 01:00:00 01:00:00
2 2014-01-01 02:00:00 02:00:00
3 2014-01-01 03:00:00 03:00:00
4 2014-01-01 04:00:00 04:00:00

print(df.dtypes)
Date     datetime64[ns]
Time    timedelta64[ns]
dtype: object