Pandas - Different time formats in the same column

后端 未结 1 422
说谎
说谎 2021-01-14 04:41

I have a Dataframe that has dates stored in different formats in the same column as shown below:

date
1-10-2018
2-10-2018
3-Oct-2018
4-10-2018
相关标签:
1条回答
  • 2021-01-14 05:02

    Use to_datetime with specify formats with errors='coerce' for replace not matched values to NaNs. Last combine_first for replace missing values by date2 Series.

    date1 = pd.to_datetime(df['date'], format='%d-%m-%Y', errors='coerce')
    date2 = pd.to_datetime(df['date'], format='%d-%b-%Y', errors='coerce')
    
    df['date'] = date1.combine_first(date2)
    print (df)
            date
    0 2018-10-01
    1 2018-10-02
    2 2018-10-03
    3 2018-10-04
    
    0 讨论(0)
提交回复
热议问题