pandas.to_datetime 使用 HKMA 的 Open 时识别正确格式的问题 API

pandas.to_datetime issue identifying correct format when using HKMA's Open API

我正在尝试确定在我获得的数据框中使用的适当格式,但我无法找到任何有效的格式。

问题是该格式包含年度数字,其中月份被假定为某种零填充的第零个月。例如,年度名义 GDP 报告为 2014-00,而不是通常的 2014-01。

因此,当我使用时,

df['end_of_month'] =pandas.to_datetime(df['end_of_month'], format="%Y-%m")

我明白了:

ValueError: time data 2014-00 doesn't match format specified

供您考虑,这里是数据框:

end_of_month  nominal_gdp
0       2014-00    2260005.0
1       2015-00    2398280.0
2       2016-00    2490617.0
3       2017-00    2662836.0
4       2018-00    2842883.0
5       2018-09     726352.0
6       2018-10          NaN
7       2018-11          NaN
8       2018-12     754904.0
9       2019-01          NaN
10      2019-02          NaN
11      2019-03     712514.0
12      2019-04          NaN
13      2019-05          NaN
14      2019-06     698044.0
15      2019-07          NaN
16      2019-08          NaN
17      2019-09     722831.0
18      2019-10          NaN
19      2019-11          NaN

对于任何有兴趣或可能面临类似问题的人,数据是从香港金融管理局使用他们的开放 API 倡议获得的。欲了解更多信息,请访问 HKMA's documentation.

具体来说,这个问题是在使用经济统计数据集时出现的,该数据集可以在以下 page 文档中找到。

看来我已经找到了解决问题的方法。这是 link 我找到解决方法的地方:

这是我使用的行:

df['end_of_month'] = pandas.to_datetime(df['end_of_month'], format='%Y-%m',errors='coerce').fillna(pandas.to_datetime(df['end_of_month'], format='%Y-00',errors='coerce'))

它只是 "fills" 具有不同格式的强制行。我用于填充零的第零个月没有意义的年度数字的格式是:“%Y-00”,因为我们可以忽略对年度频率值没有意义的“-00”。