如何通过双日期条件筛选符合入境年限要求的女性DataFrame数据?
筛选入境日期早于孩子出生日期至少两年的DataFrame数据
核心条件逻辑
因为所有日期都是纯年份格式(如2005),直接通过数值运算判断即可:孩子出生日期年份 - 入境年份 ≥ 2
代码实现(以Pandas为例)
先构造示例数据:
import pandas as pd # 构建示例DataFrame data = { "Women": ["Paula", "Andrea", "Drea"], "Date of Birth": [2005, 2004, 2001], "Date of Arrival in the Country": [2003, 2001, 2000] } df = pd.DataFrame(data)
应用筛选条件:
# 筛选符合要求的记录 filtered_df = df[df["Date of Birth"] - df["Date of Arrival in the Country"] >= 2]
筛选结果
执行后filtered_df会保留以下符合条件的记录:
| Women | Date of Birth | Date of Arrival in the Country |
|---|---|---|
| Paula | 2005 | 2003 |
| Andrea | 2004 | 2001 |
Drea的记录因2001-2000=1,不满足"至少早两年"的要求,会被排除。
额外处理(如果年份是字符串格式)
如果你的年份数据是字符串类型(比如"2005"),需要先转换为数值类型再运算:
# 将年份列转为数值类型 df["Date of Birth"] = pd.to_numeric(df["Date of Birth"]) df["Date of Arrival in the Country"] = pd.to_numeric(df["Date of Arrival in the Country"])
内容的提问来源于stack exchange,提问作者Rory2404
相关产品推荐
相关产品推荐

