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

为何Polars中with_columns无法原地修改DataFrame添加datetime列?

为什么Polars中with_columns无法原地修改原DataFrame?

核心原因

Polars的DataFrame默认采用不可变数据模型:所有数据转换类方法(包括with_columns)都不会直接修改原始DataFrame对象,而是生成并返回一个包含修改结果的新DataFrame。这种设计是为了避免意外篡改原始数据,保证数据操作的可追溯性,同时支持线程安全的并行操作。

你直接调用df.with_columns(...)但没有接收返回值,所以原df完全不会发生变化;而将返回结果赋值给新变量(如df_formated)时,自然能拿到包含新列的新DataFrame。

解决方案

如果需要更新原DataFrame,只需将with_columns的返回值重新赋值给原变量即可:

df = df.with_columns(
    pl.col('Timestamp')
      .str.strptime(pl.Datetime, "%m/%d/%Y %H:%M:%S")
      .alias('dt_f')
)

注意:Polars仅少数方法支持inplace=True参数(如drop_inplace),但with_columns并不支持原地修改。官方更推荐使用赋值的方式,以遵循不可变数据模型的设计原则,减少潜在的bug。

验证示例

修改后的代码执行后,原df会包含新的dt_f列:

print(df)
# 输出:
# shape: (3, 4)
# ┌───────────────────┬───────────┬─────────┬─────────────────────┐
# │ Timestamp         ┆ Date      ┆ Amount  ┆ dt_f                │
# │ ---               ┆ ---       ┆ ---     ┆ ---                 │
# │ str               ┆ str       ┆ str     ┆ datetime[μs]        │
# ╞═══════════════════╪═══════════╪═════════╪═════════════════════╡
# │ 4/7/2024 18:42:10 ┆ 3/19/2024 ┆ 1292.23 ┆ 2024-04-07 18:42:10 │
# │ 4/7/2024 18:42:11 ┆ 3/19/2024 ┆ 543.95  ┆ 2024-04-07 18:42:11 │
# │ 4/7/2024 18:42:12 ┆ 3/19/2024 ┆ 679.82  ┆ 2024-04-07 18:42:12 │
# └───────────────────┴───────────┴─────────┴─────────────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 15:33:13