pandas 使用德国日期格式的日期时间? [英] Pandas to datetime with German date format?
本文介绍了 pandas 使用德国日期格式的日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以以下方式显示日期的数据框:
'Jan 2019','Feb 2019','Mär 2019','Apr 2019','Mai 2019','Jun 2019','Jul 2019','Aug 2019','Sep 2019','Okt 2019','Nov 2019','Dez 2019'
我正在尝试使用
<$将列转换为日期时间p $ p>
pd.to_datetime(df.month,format ='%b%Y',errors ='ignore')
不幸的是, to_datetime
会重新调整对象而不是日期时间。我认为这是因为日期的德语拼写(例如,Mär2019而不是 Mar 2019或 Dez 2019而不是 Dec 2019)。
什么是解决该问题的通用方法?
解决方案
我认为一种可能的解决方案是使用 Series.replace
转换为日期时间之前:
a = ['Jan 2019','Feb 2019','Mär2019' ,'Apr 2019','Mai 2019',
'Jun 2019','Jul 2019','Aug 2019','Sep 2019','Okt 2019','Nov 2019','Dez 2019']
df = pd.DataFrame({'month':a})
d = {'Mär':'Mar','Mai':'May','Okt ':'Oct','Dez':'Dec'}
df ['month'] = pd.to_datetime(df ['month']。replace(d,regex = True),format ='%b %Y',errors ='coerce')
print(df)
month
0 2019-01-01
1 2019-02-01
2 2019- 03-01
3 2019-04-01
4 2019-05-01
5 2019-06-01
6 2019-07-01
7 2019-08-01
8 2019-09-01
9 2019-10-01
10 2019-11-01
11 2019-12-01
I have a dataframe with dates in the following manner:
'Jan 2019', 'Feb 2019', 'Mär 2019', 'Apr 2019', 'Mai 2019', 'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Okt 2019', 'Nov 2019', 'Dez 2019'
I am trying to convert the column to datetime using
pd.to_datetime(df.month, format='%b%Y', errors='ignore')
Unfortunately, to_datetime
retuns objects instead of datetimes. I believe it's because of the German spelling of the date (e.g. 'Mär 2019' instead of 'Mar 2019' or 'Dez 2019' instead of 'Dec 2019').
What would be a good general solution to this problem?
解决方案
I think one possible solution is use Series.replace
before converting to datetimes:
a = ['Jan 2019', 'Feb 2019', 'Mär 2019', 'Apr 2019', 'Mai 2019',
'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Okt 2019', 'Nov 2019', 'Dez 2019']
df = pd.DataFrame({'month':a})
d = {'Mär':'Mar', 'Mai':'May','Okt':'Oct','Dez':'Dec'}
df['month']=pd.to_datetime(df['month'].replace(d, regex=True), format='%b %Y', errors='coerce')
print (df)
month
0 2019-01-01
1 2019-02-01
2 2019-03-01
3 2019-04-01
4 2019-05-01
5 2019-06-01
6 2019-07-01
7 2019-08-01
8 2019-09-01
9 2019-10-01
10 2019-11-01
11 2019-12-01
这篇关于 pandas 使用德国日期格式的日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文