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

如何过滤Pandas Series中2017年及以后的日期索引数据?

过滤Pandas Series中2017年及以后的数据

嘿,我来帮你搞定这个过滤需求!你已经通过frame['date_created'].value_counts().sort_index()得到了这样一个按日期索引排序的Series:

2013-10     1
2014-12     1
2015-02     1
2015-03     1
2015-09     1
2016-02     6
2016-03     1
2017-05     5
2017-07     2
2017-08    13
2017-09    40
2017-10    47
2017-11    40
2017-12    26
2018-01    16
dtype: int64

这里有两种实用的方法可以过滤出2017年及以后的数据:

方法一:基于字符串前缀筛选(适合索引为字符串类型)

如果你的Series索引是YYYY-MM格式的字符串,可以直接通过判断索引的前缀来筛选:

# 先给你的Series起个方便的名字,比如date_counts
date_counts = frame['date_created'].value_counts().sort_index()
# 筛选2017及以后的条目
filtered_series = date_counts[date_counts.index.str.startswith('2017') | date_counts.index.str.startswith('2018')]

这种方法简单直接,适合当前你的数据范围,但如果后续有2019、2020等年份,需要手动补充条件。

方法二:转为Datetime类型筛选(更灵活严谨)

推荐用这种方法,把索引转换成datetime类型后,就能用日期比较来筛选,扩展性更好:

date_counts = frame['date_created'].value_counts().sort_index()
# 临时转换索引为datetime进行判断(不修改原Series)
filtered_series = date_counts[pd.to_datetime(date_counts.index) >= '2017-01-01']

如果想永久修改索引类型,也可以这样做:

date_counts = frame['date_created'].value_counts().sort_index()
# 将索引转为datetime类型
date_counts.index = pd.to_datetime(date_counts.index)
# 筛选2017年及以后的数据
filtered_series = date_counts[date_counts.index >= '2017-01-01']

这种方法不管后续新增多少年份,都能自动匹配2017及以后的数据,逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:30:11