在pandas中使用混合日期时间格式

2024-10-04 11:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个文件读入一个数据框,其中日期的格式各不相同:

  • 要么是美国人:YYYY-MM-DD

  • 或者欧洲人:DD.MM.YYYY

它们就像一根绳子。我想将它们全部格式化为一个日期对象,这样pandas.Series.dt就可以使用它们,理想情况下,它们可以采用第二种格式(DD.MM.YYYY

pandas.Series.dt与一列中的两种不同拼写混淆


Tags: 文件数据对象pandas格式dt情况dd
2条回答

^{}分别用于两种格式,如果格式不匹配,则获取缺少的值,因此对于新列,请使用^{}

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中的datetimes格式默认为YYYY-MM-DD,如果需要自定义,则可以,但值会转换为字符串,因此datetimelike函数失败:

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.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]

相关问题 更多 >