在Pandas数据框中转换日期格式 [英] Converting date formats in pandas dataframe

查看:92
本文介绍了在Pandas数据框中转换日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,日期"列有两种不同类型的日期格式.

I have a dataframe and the Date column has two different types of date formats going on.

eg. 1983-11-10 00:00:00 and 10/11/1983

我希望它们都是同一类型,如何遍历数据框的日期"列并将日期转换为一种格式?

I want them all to be the same type, how can I iterate through the Date column of my dataframe and convert the dates to one format?

推荐答案

我相信您需要dayfirst=True .to_datetime.html"rel =" nofollow noreferrer> to_datetime :

I believe you need parameter dayfirst=True in to_datetime:

df = pd.DataFrame({'Date': {0: '1983-11-10 00:00:00', 1: '10/11/1983'}})
print (df)
                  Date
0  1983-11-10 00:00:00
1           10/11/1983


df['Date'] = pd.to_datetime(df.Date, dayfirst=True)
print (df)
        Date
0 1983-11-10
1 1983-11-10

因为:

df['Date'] = pd.to_datetime(df.Date)
print (df)
        Date
0 1983-11-10
1 1983-10-11


或者您可以指定两种格式,然后使用 combine_first :


Or you can specify both formats and then use combine_first:

d1 = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S', errors='coerce')
d2 = pd.to_datetime(df.Date, format='%d/%m/%Y', errors='coerce')

df['Date'] = d1.combine_first(d2)
print (df)
        Date
0 1983-11-10
1 1983-11-10

多种格式的通用解决方案:

General solution for multiple formats:

from functools import reduce 

def convert_formats_to_datetimes(col, formats):
    out = [pd.to_datetime(col, format=x, errors='coerce') for x in formats]
    return reduce(lambda l,r: pd.Series.combine_first(l,r), out)

formats = ['%Y-%m-%d %H:%M:%S', '%d/%m/%Y']
df['Date'] = df['Date'].pipe(convert_formats_to_datetimes, formats)
print (df)
        Date
0 1983-11-10
1 1983-11-10

这篇关于在Pandas数据框中转换日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆