python-3.x - 在 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')
解决方案
你可以尝试这样的事情:
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,则必须创建一个新的日列。
推荐阅读
- forms - Microsoft Access:视图模式下的表单高度大小与设计模式下的高度不匹配
- windows - Windows 10 上的 Docker:如何将现有容器和映像移动到新位置?
- c# - 是否可以轻松修复我的代码以使 mysql Update 语句在 csharp 中工作?
- python - 我的 TensorFlow 输入函数中的错误:“TypeError:预期单个张量时的张量列表”
- vue.js - 每个组件的 Vue 实例超过单个实例
- java - 为什么 jacobs “new ActiveXComponent” 在与 Redemption 一起使用时有时会抛出“无法共同创建对象”?
- spring-boot - Spring Data Neo4j MappingException:实体的主 ID 字段为空
- qt - 如何使组合框项目在 qml 中不可选择?
- c# - 计算数组中的元素 - 性能 -
- python - 当每个脚本在 python 中有多个线程时,从主脚本同时运行两个脚本