python - 根据年龄和日期列查找近似 DOB
问题描述
我在数据框中有三列:start_date、age 和 DOB。但是缺少一些 DOB 信息,而 start_date 和 age 则没有。我希望使用以下公式估算 DOB 列的空单元格,并使用近似的 DOB:start_date - age。
数据框示例:
start_date | age | DOB
3/1/2017 87 11/1/1930
9/13/2017 31
7/26/2017 60
7/26/2017 52
4/1/2017 37 12/14/1979
我的问题是如何执行此操作,仅在数据框 DOB 列的空单元格上执行?有什么简单的方法吗?
谢谢并恭祝安康
解决方案
这是一种方法:
df.DOB = pd.to_datetime(df.DOB)
estimated_dob = pd.to_datetime(df.start_date) - pd.to_timedelta(df.age, unit='y')
df.loc[df.DOB.isna(), "DOB"] = estimated_dob[df.DOB.isna()]
#to remove the time part of the timestamp:
df["DOB"] = df["DOB"].dt.date
结果是:
start_date age DOB
0 3/1/2017 87 1930-11-01
1 9/13/2017 31 1986-09-13
2 7/26/2017 60 1957-07-26
3 7/26/2017 52 1965-07-26
4 4/1/2017 37 1979-12-14
推荐阅读
- asp.net-mvc - 验证并检查文本框的条件和约束
- c# - 我需要创建一个系统,其中包含用户使用 aspnet 核心在 UI 上创建/编辑的动态规则
- javascript - 错误:TypeError:对象原型可能只是一个对象或空:未定义
- java - 在 Java 中的字符串向量元素处更改一个“字符”
- javascript - VueJs 可拖动对象动画
- c - 我有一个字符串,我想删除任何 - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' 从单词的开头或结尾
- android - 有没有办法实现路由器来管理 Android 上的片段?
- java - 以编程方式触发 MouseMove java
- sql - Oracle - 将持续时间与不同的 15 分钟间隔相关联
- python - Selenium 单击并选择下拉值(jsslot)