Merging Datetime column and Int column as hours replacing 00 - ValueError: to assemble mappings requires at least that [year, month, day]

Merging Datetime column and Int column as hours replacing 00 - ValueError: to assemble mappings requires at least that [year, month, day]

我有一个包含两列的数据框:

它们代表一天和一个小时。 我想合并,因为那时我想给 prophet 所以我需要转换成这种格式:

YYYY-MM-DD HH:MM:SS

我这样试过:

example={"date":["2018-04-18","2018-04-18","2018-04-18"],"alert_h":[4,17,23]}

df=pd.DataFrame(example)

df['date']=pd.to_datetime(df['date']) #I am converting str to datetime just for creating the example, I have already in the original df a datetime format

df.assign(date_h=pd.to_datetime(df[['date','alert_h']], format='%Y-%m-%d %h'))

我收到以下错误消息。

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day,month,year] is missing

我阅读了以下问题:

如果这是重复的,请随时关闭这个问题我会研究任何其他问题 link 因为我找不到解决我的问题的具体问题。

第一种方法:

newdf=df['date'].str.split('-',expand=True).assign(hour=df['alert_h'])
newdf=newdf.astype(str)
newdf.columns=['year','month','day','hour']
df['date_h']=pd.to_datetime(newdf,format='%Y-%m-%d %h:%m:%s')

第二种方法:

example={"date":["2018-04-18","2018-04-18","2018-04-18"],"alert_h":[4,17,23]}
df=pd.DataFrame(example)
date_h=df['date']+' '+df['alert_h'].astype(str)+':00:00'
df['date']=pd.to_datetime(df['date'])
df['date_h']=pd.to_datetime(date_h)

编辑(第三种方法):

方法@MrFuppes(效率更高):

df['date_h']=pd.to_datetime(df['date']) + pd.to_timedelta(df['alert_h'], unit='h')