首页 > 解决方案 > 在 pd 中创建日期时处理 ValueError

问题描述

我正在读取一个 csv 文件p, day, month,并将其放入df. 目标是从日、月、当年创建一个日期,我在 2 月 29 日遇到了这个错误:

ValueError: cannot assemble the datetimes: day is out of range for month

我想在发生此错误时,将前一天替换为前一天。我们怎么能做到这一点?下面是我的 pd 的几行,datex最后是我想要得到的

        p  day month  year datex
0      p1  29    02  2021  28Feb-2021
1      p2  18    07  2021  18Jul-2021
2      p3  12    09  2021  12Sep-2021

现在,我的日期代码只有下面,所以我有 nan 日期不存在的地方。

df['datex'] = pd.to_datetime(df[['year', 'month', 'day']], errors='coerce')

标签: python-3.xpandasdatetimevalueerror

解决方案


你可以尝试这样的事情:

df['datex'] = pd.to_datetime(df[['year', 'month', 'day']], errors='coerce')

事实上,你得到 NA :

    p  day  year  month      datex
0  p1   29  2021      2        NaT
1  p2   18  2021      7 2021-07-18
2  p3   12  2021      9 2021-09-12

然后你可以为这些 NA 做一个特殊的案例:

df.loc[df.datex.isnull(), 'previous_day'] = df.day -1

    p  day  year  month      datex  previous_day
0  p1   29  2021      2        NaT          28.0
1  p2   18  2021      7 2021-07-18           NaN
2  p3   12  2021      9 2021-09-12           NaN

df.loc[df.datex.isnull(), 'datex'] = pd.to_datetime(df[['previous_day', 'year', 'month']].rename(columns={'previous_day': 'day'}))

    p  day  year  month      datex  previous_day
0  p1   29  2021      2 2021-02-28          28.0
1  p2   18  2021      7 2021-07-18           NaN
2  p3   12  2021      9 2021-09-12           NaN

如果要在日列中保留 day = 29,则必须创建一个新的日列。


推荐阅读