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

如何筛选pandas DataFrame日期列中晚于2015-12的数据行

解决方案

问题原因

你的报错核心是date列未统一转换为日期类型,字符串格式不统一(部分为年-月、部分为年-月-日)导致比较逻辑异常,同时列维度不匹配触发了值错误。

正确实现步骤

  1. 先将date列统一转换为pandas内置的datetime类型,自动兼容不同长度的日期格式:
import pandas as pd
df['date'] = pd.to_datetime(df['date'], errors='coerce')
  1. 执行筛选操作,以下两种方式均可:
  • 方式1:直接和日期边界值比较
# 晚于2015年12月等价于日期大于2015年12月31日
filtered_df = df[df['date'] > pd.to_datetime('2015-12-31')]
# 重置索引获得和预期结果一致的序号
filtered_df = filtered_df.reset_index(drop=True)
  • 方式2:按年月维度直接比较
# 生成年月维度字段后比较
df['year_month'] = df['date'].dt.to_period('M')
filtered_df = df[df['year_month'] > pd.Period('2015-12')].drop('year_month', axis=1).reset_index(drop=True)

运行后filtered_df就是你需要的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:24:06