将数据框转换为熊猫日期时间格式

时间:2018-07-17 13:06:38

标签: python-3.x pandas

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

df1:

       DOU  Hr_y Min_y  Sec_y  Hr_x  Min_x  Sec_x
2017-09-02    12     5     16    16      5     16
2017-09-02    14    21     45    21      6     30

我想将Hr_y,Min_y,Sec_y,Hr_x,Min_x,Sec_x转换为熊猫日期时间格式。

那是什么语法?

1 个答案:

答案 0 :(得分:0)

您可以按hourminute s和second s创建timedeltas并添加到datetime s中。

df['DOU'] = pd.to_datetime(df['DOU'])

a = pd.to_timedelta(df.filter(regex='y$').astype(str).apply(':'.join, 1))
b = pd.to_timedelta(df.filter(regex='x$').astype(str).apply(':'.join, 1))

df['x'] = df['DOU'] + a
df['y'] = df['DOU'] + b
print (df)
         DOU  Hr_y  Min_y  Sec_y  Hr_x  Min_x  Sec_x                   x  \
0 2017-09-02    12      5     16    16      5     16 2017-09-02 12:05:16   
1 2017-09-02    14     21     45    21      6     30 2017-09-02 14:21:45   

                    y  
0 2017-09-02 16:05:16  
1 2017-09-02 21:06:30  

另一种解决方案是将所有列连接在一起,然后转换为日期时间:

df['x'] = pd.to_datetime(df['DOU'].astype(str) + 
                        df['Hr_x'].astype(str) + 
                        df['Min_x'].astype(str) + 
                       df['Sec_x'].astype(str), format='%Y-%m-%d%H%M%S')

df['y'] = pd.to_datetime(df['DOU'].astype(str) + 
                        df['Hr_y'].astype(str) + 
                        df['Min_y'].astype(str) + 
                       df['Sec_y'].astype(str), format='%Y-%m-%d%H%M%S')
print (df)
          DOU  Hr_y  Min_y  Sec_y  Hr_x  Min_x  Sec_x                   x  \
0  2017-09-02    12      5     16    16      5     16 2017-09-02 16:51:06   
1  2017-09-02    14     21     45    21      6     30 2017-09-02 21:06:30   

                    y  
0 2017-09-02 12:51:06  
1 2017-09-02 14:21:45