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

使用pandas.to_datetime()结合loc[]与比较运算符时过滤失效求助

解决日期过滤无效的问题

核心错误原因

你写的pd.Timestamp(2018-1-1)会先执行整数运算,结果是2016,pandas会把这个整数当成Unix时间戳解析,对应时间是1970-01-01 00:00:02.016,你的所有数据日期都远大于这个时间,所以过滤后返回全量数据。另外,转换日期时用format='%Y-%m-%d'也不符合原数据YYYY-MM的格式,虽然pandas可能自动补全,但规范写法能避免潜在问题。

正确操作步骤

  1. 修正日期转换格式
    原数据是YYYY-MM字符串,转换时匹配对应格式:
df["year_month"] = pd.to_datetime(df["year_month"], format='%Y-%m')

转换后该列会变成datetime64[ns]类型,日期自动补全为当月第一天(比如2001-01转为2001-01-01)。

  1. 正确编写过滤条件
    用字符串或正确的Timestamp构造方式指定过滤日期,不要用整数运算:
# 方式1:直接传入日期字符串,简洁明了
filtered_df = df.loc[df["year_month"] >= "2018-01-01"]

# 方式2:明确构造Timestamp对象
filtered_df = df.loc[df["year_month"] >= pd.Timestamp("2018-01-01")]

# 方式3:因为year_month是当月第一天,也可以直接用年月字符串过滤
filtered_df = df.loc[df["year_month"] >= pd.Timestamp("2018-01")]

额外优化:读取CSV时直接解析日期

如果第一次用parse_dates没生效,是因为pandas自动推断格式失败,读取时直接指定日期格式就能一步到位:

df = pd.read_csv(
    'C:/..../migration_flows.csv',
    parse_dates=["year_month"],
    date_format='%Y-%m'
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:45:39