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

从Pandas转用Polars:如何为DataFrame添加单一字符串新列

Pandas转Polars:添加固定值新列的实现方法

方法1:使用with_columns(Polars推荐的链式调用方式)

Polars中添加常量值列需要用pl.lit()包装固定值,再通过with_columns方法添加:

import polars as pl

df = pl.DataFrame({'existing_column': [1, 2, 3]})
# 添加固定文本的新列
df = df.with_columns(pl.lit('some text').alias('new_column'))

方法2:使用assign(贴近Pandas使用习惯)

如果习惯Pandas的assign写法,Polars也支持直接传入常量值:

import polars as pl

df = pl.DataFrame({'existing_column': [1, 2, 3]})
df = df.assign(new_column='some text')

两种方法执行后,得到的DataFrame都符合预期:

existing_columnnew_column
1some text
2some text
3some text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:03:18