Pandas:如何将整数格式出生日期转换为基于估值日的年龄
问题原因
直接将整数格式的YYYYMMDD日期传入pd.to_datetime()时,pandas默认会将整数识别为Unix纳秒时间戳,而非按年/月/日格式解析,所以得到的日期差值完全不符合预期。
实现代码
以下代码可以匹配你给出的期望输出:
import pandas as pd from io import StringIO # 构造原始DataFrame dfs = """ BornDate 2 19850100 3 19000100 5 19850100 6 19000100 7 19820100 8 19850100 9 19000100 10 19790100 11 19850100 """ df = pd.read_csv(StringIO(dfs.strip()), sep='\s+', dtype={"BornDate": int}) ValuationDate = 20201231 # 提取估值日的年份和月份 val_year = int(str(ValuationDate)[:4]) val_month = int(str(ValuationDate)[4:6]) # 提取出生日期的年份、月份 df['birth_year'] = df['BornDate'].astype(str).str[:4].astype(int) df['birth_month'] = df['BornDate'].astype(str).str[4:6].astype(int) # 按规则计算年龄 df['BornDate'] = (val_year - df['birth_year']) + df['birth_month'] / 10 # 输出结果 print(df['BornDate'])
运行后输出如下(你给出的期望结果中第3行的12.01为笔误,正确结果应为120.1):
2 35.1 3 120.1 5 35.1 6 120.1 7 38.1 8 35.1 9 120.1 10 41.1 11 35.1 Name: BornDate, dtype: float64
如果你需要按实际日期差计算更精准的年龄(考虑闰年、具体天数),可以使用以下方案:
ValuationDate = 20201231 # 按YYYYMMDD格式解析估值日 val_date = pd.to_datetime(ValuationDate, format='%Y%m%d') # 将出生日期最后两位的00替换为01后解析为日期 df['born_dt'] = pd.to_datetime(df['BornDate'].astype(str).str.replace(r'00$', '01', regex=True), format='%Y%m%d') # 计算年龄:总天数除以365.25后保留1位小数 df['BornDate'] = ((val_date - df['born_dt']).dt.days / 365.25).round(1)
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

