如何在 pandas 数据框中合并 datetime.date 和 datetime.time 列?

her*_*lla 5 python datetime dataframe python-3.x pandas

给定 df

          Date      Time    Data     
3   2017-08-10  15:15:00    a    
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    
Run Code Online (Sandbox Code Playgroud)

print (type(df['Date'].iat[0]))
<class 'datetime.date'>

print (type(df['Time'].iat[0]))
<class 'datetime.time'>
Run Code Online (Sandbox Code Playgroud)

如何将 df.Date 和 df.Time 合并到作为日期时间对象的 DateTime 列中?:

        Date        Time    Data  DateTime   
3   2017-08-10  15:15:00    a     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
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

df['DateTime'] = df.apply(lambda r : pd.datetime.combine(r['Date'],r['Time']),1)
Run Code Online (Sandbox Code Playgroud)

这按预期工作得很好,但是,我更喜欢矢量化操作,并且我得到以下消息:

C:\Users\User\Anaconda3\lib\site-packages\ipykernel\__main__.py:1: 
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-
docs/stable/indexing.html#indexing-view-versus-copy
if __name__ == '__main__':
Run Code Online (Sandbox Code Playgroud)

Vai*_*ali 2

这里的问题是日期和时间都已经是日期时间格式。尝试

df['datetime'] = pd.to_datetime(df['Date'].dt.strftime('%Y-%m-%d') + df['Time'].astype(str), format = '%Y-%m-%d%H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

虽然我不知道它是否比使用 datetime.combine 更有效