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

如何按特定时间(忽略日期)筛选Polars DataFrame?

如何在Polars DataFrame中筛选出所有中午12点的记录?

我有一个存储每15分钟采样电力需求数据的Polars DataFrame,时间跨度为一整月,数据示例如下:

df.head()
    shape: (5, 2)
    date    demande
    datetime[μs]    u32
    2024-01-14 00:00:00 25721
    2024-01-14 00:15:00 25558
    2024-01-14 00:30:00 25461
    2024-01-14 00:45:00 25507
    2024-01-14 01:00:00 25608

需要筛选出所有中午12点的记录,期望结果如下:

sub_df.head()
    shape: (5, 2)
    date    demande
    datetime[μs]    f64
    2024-01-14 12:00:00 28078
    2024-01-15 12:00:00 30575
    2024-01-16 12:00:00 30815
    2024-01-17 12:00:00 29944
    2024-01-18 12:00:00 29850

我已经掌握按需求值筛选的方法:

critical_demand_df = df.filter(pl.col("demande") > 35000)

但尝试类似代码筛选时间时:

sub_df = df.filter(pl.col("date").hour == 12)

出现错误:

AttributeError: 'Expr' object has no attribute 'hour'

解决方案

Polars中处理datetime类型列的表达式需要通过dt访问器调用相关方法,而非直接访问属性。以下是几种简洁的实现方式:

  1. 仅筛选小时为12的记录(适配你的15分钟采样数据,仅12:00:00会满足小时=12且分钟=0):
sub_df = df.filter(pl.col("date").dt.hour() == 12)
  1. 严谨筛选12:00:00整的记录(同时匹配小时和分钟):
sub_df = df.filter((pl.col("date").dt.hour() == 12) & (pl.col("date").dt.minute() == 0))
  1. 直接匹配时间值:
sub_df = df.filter(pl.col("date").dt.time() == pl.time(12, 0, 0))

以上方法都能正确筛选出所有中午12点整的记录,其中第一种写法最为简洁,适合你的数据场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:03:29