在 pandas 中使用混合的日期时间格式 [英] Working with mixed datetime formats in pandas
问题描述
我将文件读入大熊猫数据框中,其日期的格式有所不同:
I read a file into a pandas dataframe with dates that vary in their format:
-
两个美国人:
YYYY-MM-DD
或欧洲语言: DD.MM.YYYY
它们以字符串形式出现。我想将它们全部格式化为日期对象,以便 pandas.Series.dt
可以与它们一起使用,并理想地采用第二种格式( DD .MM.YYYY
)。
They come as a string. I would like to format them all as a date object so pandas.Series.dt
can work with them and ideally have them in the second format (DD.MM.YYYY
).
pandas.Series.dt
与
pandas.Series.dt
gets confuesed with the two different spellings in one column.
推荐答案
使用 to_datetime
分别使用两种格式,因此如果使用format则缺少值不匹配,因此对于新列,请使用 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
并理想地采用第二种格式
and ideally have them in the second format
python / pandas中日期时间的格式为默认情况下 YYYY-MM-DD
,如果需要自定义,则可以,但是将值转换为字符串,因此datetimelike函数失败:
Format of datetimes in python/pandas is by default YYYY-MM-DD
, if need custom one it is possible, but values are converted to strings, so datetimelike functions failed:
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'>
这篇关于在 pandas 中使用混合的日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!