You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas中如何对存储日期的Series匹配指定年份返回布尔结果?

解决方法

直接使用Series的字符串匹配方法str.contains即可满足需求,该方法会逐元素检查字符串是否包含传入的子串,返回对应的布尔序列。
补全后的完整可运行代码:

import pandas as pd

date_series = pd.Series(["1 jan 2022", "2021-01-31", "19 dec 2016"])
print(date_series.str.contains("2021"))

运行输出结果和预期完全匹配:

0    False
1     True
2    False
dtype: bool

注意:如果业务场景中存在日期字符串的非年份位置出现"2021"字符的特殊情况,建议先用pd.to_datetime把序列转换为标准日期类型后再按年份判断,避免匹配错误,参考写法:

date_series_dt = pd.to_datetime(date_series)
print(date_series_dt.dt.year == 2021)

内容的提问来源于stack exchange,提问作者Kai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:55:05