How to make two different date format in single column unique?

后端 未结 3 832
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 03:36

I have one column in I don\'t understand how but there is two different format in a single column.

df[\'Date\'] = [6/24/2019,6/14/2019,2019-09-06 00:00:00,6/         


        
3条回答
  •  星月不相逢
    2020-12-22 04:25

    Use to_datetime with both formats and errors='coerce' for NaT if not match and replace missing values by another Series by Series.combine_first or Series.fillna them, last convert to strings by Series.dt.strftime:

    s1 = pd.to_datetime(data['Date'], format='%Y-%d-%m %H:%M:%S', errors='coerce')
    s2 = pd.to_datetime(data['Date'], format = '%m/%d/%Y', errors='coerce')
    
    #2 possible solutions
    data['new'] = s1.fillna(s2).dt.strftime('%m/%d/%Y')
    data['new'] = s1.combine_first(s2).dt.strftime('%m/%d/%Y')
    print (data)
                      Date         new
    0            6/24/2019  06/24/2019
    1            6/14/2019  06/14/2019
    2  2019-09-06 00:00:00  06/09/2019
    3            6/14/2019  06/14/2019
    4            6/14/2019  06/14/2019
    

提交回复
热议问题