首页 > 解决方案 > 根据年龄和日期列查找近似 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 列的空单元格上执行?有什么简单的方法吗?

谢谢并恭祝安康

标签: python

解决方案


这是一种方法:

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

推荐阅读