Python 使用datetime组合日期和时间列

Python 使用datetime组合日期和时间列,python,pandas,datetime,dataframe,anaconda,Python,Pandas,Datetime,Dataframe,Anaconda,我正在尝试将日期合并到数据框中的多个时间列中。我可以遍历每一行,但我对如何组合列感到困惑。例如: date first_time second_time .... 0 2008/09/11 12:32 17:56 1 2016/12/02 06:43 14:02 2 2001/01/01 02:45 20:13 . . . 使用.ItErrors,我可以将其分解为每一行。因此,行['date']将是该特

我正在尝试将日期合并到数据框中的多个时间列中。我可以遍历每一行,但我对如何组合列感到困惑。例如:

   date        first_time   second_time .... 
0  2008/09/11    12:32        17:56
1  2016/12/02    06:43        14:02
2  2001/01/01    02:45        20:13
.
.
.
使用.ItErrors,我可以将其分解为每一行。因此,行['date']将是该特定列的日期。但是,我需要使用datetime将日期与每个列组合起来。我在网上不断发现各种方法的错误。如果我有行['date']和行['first_time'],我如何在数据框中将它们与date和每隔一个时间列合并

最终结果应该是:

    first_datetime      second_datetime    .... 
0  2008/09/11 12:32     2008/09/11 17:56 
1  2016/12/02 06:43     2016/12/02 14:02 
2  2001/01/01 02:45     2001/01/01 20:13 
.
.
.
您可以先使用列日期,然后在时间循环中转换列:

有关更动态的解决方案,请仅转换名称中包含时间的列:

df = df.set_index('date')
for col in df.columns:
    df[col] = pd.to_datetime(df.index + df[col], format='%Y/%m/%d%H:%M')
#if necessary rename columns
df.columns = df.columns.str.replace('time','datetime')
df = df.reset_index(drop=True)
print (df)
       first_datetime     second_datetime
0 2008-09-11 12:32:00 2008-09-11 17:56:00
1 2016-12-02 06:43:00 2016-12-02 14:02:00
2 2001-01-01 02:45:00 2001-01-01 20:13:00

print (df.dtypes)
first_datetime     datetime64[ns]
second_datetime    datetime64[ns]
dtype: object
df = df.set_index('date')
#extract only time columns
cols = df.columns[df.columns.str.contains('time')]
for col in cols:
    df[col] = pd.to_datetime(df.index + df[col], format='%Y/%m/%d%H:%M')
df.columns = df.columns.str.replace('time','datetime')
df = df.reset_index(drop=True)
print (df)
       first_datetime     second_datetime
0 2008-09-11 12:32:00 2008-09-11 17:56:00
1 2016-12-02 06:43:00 2016-12-02 14:02:00
2 2001-01-01 02:45:00 2001-01-01 20:13:00