我将文件读入pandas数据框中,其日期的格式不同:
任美国人:YYYY-MM-DD
或欧洲人:DD.MM.YYYY
它们作为字符串来。我想将它们全部格式化为日期对象,以便pandas.Series.dt
可以与它们一起使用,理想情况下将它们设置为第二种格式(DD.MM.YYYY
)。
pandas.Series.dt
在一列中混淆了两种不同的拼写。
答案 0 :(得分:1)
分别对两种格式使用to_datetime
,因此如果格式不匹配,则会缺少值,因此对于新列,请使用Series.fillna
:
df = pd.DataFrame({'date': ['2000-01-12', '2015-01-23', '20.12.2015', '31.12.2009']})
print (df)
date
0 2000-01-12
1 2015-01-23
2 20.12.2015
3 31.12.2009
date1 = pd.to_datetime(df['date'], errors='coerce', format='%Y-%m-%d')
date2 = pd.to_datetime(df['date'], errors='coerce', format='%d.%m.%Y')
df['date'] = date1.fillna(date2)
print (df)
date
0 2000-01-12
1 2015-01-23
2 2015-12-20
3 2009-12-31
理想情况下,使用第二种格式
Python / pandas中的日期时间格式默认为YYYY-MM-DD
,如果需要自定义,则可以,但是值会转换为字符串,因此类似datetime的函数会失败:
df['date'] = df['date'].dt.strftime('%d.%m.%Y')
print (df)
date
0 12.01.2000
1 23.01.2015
2 20.12.2015
3 31.12.2009
print (type(df.loc[0, 'date']))
<class 'str'>
答案 1 :(得分:0)
只需检查两种格式中的哪一种,然后使用该格式应用pandas.to_datetime
。
df = pd.DataFrame({'date': ['2000-01-12', '2015-01-23', '20.12.2015',
'31.12.2009']})
print(df)
date
0 2000-01-12
1 2015-01-23
2 20.12.2015
3 31.12.2009
def date_formator(date):
if '-' in date:
return pd.to_datetime(date, format = '%Y-%m-%d')
else:
return pd.to_datetime(date, format = '%d.%m.%Y')
df.date.apply(date_formator)
0 2000-01-12
1 2015-01-23
2 2015-12-20
3 2009-12-31
Name: date, dtype: datetime64[ns]