熊猫-同一列中的不同时间格式
问题内容:
我有一个数据框,其日期以不同的格式存储在同一列中,如下所示:
date
1-10-2018
2-10-2018
3-Oct-2018
4-10-2018
无论如何,我可以使它们全部具有相同的格式。
问题答案:
to_datetime
与指定格式一起使用,errors='coerce'
用于将不匹配的值替换为NaN
。最后combine_first
用于按date2
序列替换缺少的值。
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