无法合并Pandas中的日期和时间

2024-10-01 05:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

供参考:

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

有人能帮我吗


Tags: to代码datetimedatetime错误时间out
1条回答
网友
1楼 · 发布于 2024-10-01 05:00:44

您可以直接使用timedelta64[ns]连接datetime64[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

相关问题 更多 >