How can I split a DataFrame column with datetimes into two columns: one with dates and one with times of the day?

后端 未结 4 1607
有刺的猬
有刺的猬 2021-01-19 00:26

I have a data frame called data, which has a column Dates like this,

                 Dates
0  2015-05-13 23:53:00
1  2015-05-13 23         


        
4条回答
  •  既然无缘
    2021-01-19 00:54

    attrgetter + pd.concat + join

    You can use operator.attrgetter with pd.concat to add an arbitrary number of datetime attributes to your dataframe as separate series:

    from operator import attrgetter
    
    fields = ['date', 'time']
    df = df.join(pd.concat(attrgetter(*fields)(df['Date'].dt), axis=1, keys=fields))
    
    print(df)
    
                     Date        date      time
    0 2015-05-13 23:53:00  2015-05-13  23:53:00
    1 2015-01-13 15:23:00  2015-01-13  15:23:00
    2 2016-01-13 03:33:00  2016-01-13  03:33:00
    3 2018-02-13 20:13:25  2018-02-13  20:13:25
    4 2017-05-12 06:52:00  2017-05-12  06:52:00
    

提交回复
热议问题