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

如何替换Polars DataFrame中Datetime列的年份

如何将Polars DataFrame中Datetime列的年份统一替换为指定值?

核心解决方案:使用Polars内置的dt.year.set()方法

Polars提供了直接修改Datetime字段年份的API,无需拆分重组时间组件,简洁高效。

完整代码示例:

import polars as pl

df = pl.from_repr("""
┌─────────────────────┐
│ Index               │
│ ---                 │
│ datetime[ns]        │
╞═════════════════════╡
│ 2017-01-01 00:00:00 │
│ 2017-01-01 01:00:00 │
│ 2017-01-01 02:00:00 │
│ 2017-01-01 03:00:00 │
│ 2019-12-31 20:00:00 │
│ 2019-12-31 21:00:00 │
│ 2019-12-31 22:00:00 │
│ 2019-12-31 23:00:00 │
└─────────────────────┘
""")

# 将"Index"列的年份替换为2022
df = df.with_columns(
    pl.col("Index").dt.year.set(2022).alias("Index")
)

print(df)

执行后输出结果:

┌─────────────────────┐
│ Index               │
│ ---                 │
│ datetime[ns]        │
╞═════════════════════╡
│ 2022-01-01 00:00:00 │
│ 2022-01-01 01:00:00 │
│ 2022-01-01 02:00:00 │
│ 2022-01-01 03:00:00 │
│ 2022-12-31 20:00:00 │
│ 2022-12-31 21:00:00 │
│ 2022-12-31 22:00:00 │
│ 2022-12-31 23:00:00 │
└─────────────────────┘

备选方案:拆分时间组件后重组

如果需要更灵活的时间字段修改(比如同时调整多个组件),可以提取原Datetime的月、日、时等信息,再重新构造Datetime:

df = df.with_columns(
    pl.datetime(
        year=2022,
        month=pl.col("Index").dt.month(),
        day=pl.col("Index").dt.day(),
        hour=pl.col("Index").dt.hour(),
        minute=pl.col("Index").dt.minute(),
        second=pl.col("Index").dt.second()
    ).alias("Index")
)

不过这种方式代码冗余,效率不如第一种方法,推荐优先使用dt.year.set()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:15:41