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

Polars-Python多列字符串替换报错:with_columns()参数数量不符

解决Polars中with_columns()参数错误及多字符串替换问题

错误原因

你遇到的with_columns() takes from 1 to 2 positional arguments but 4 were given错误,是因为调用with_columns()时参数传递方式不符合要求:旧版本Polars中,该方法仅接受1个位置参数(除了DataFrame自身),即需要将多个表达式打包成列表传入,而非直接传递多个独立的表达式。

同时你的代码逻辑存在问题:直接对同一列多次调用str.replace()并作为独立表达式传入,会生成多个同名的text列,这并非你想要的多内容替换效果。


正确实现方式

方式1:链式调用str.replace()(适合少量替换规则)

对同一列依次执行替换操作,链式调用str.replace(),并将整个链式表达式传入with_columns():

import polars as pl 
df = pl.DataFrame({"id": [1, 2,3,4,5], "text": ["abc", "abc","cde","cde","fgh"]})
df2 = df.with_columns(
    pl.col("text")
    .str.replace(r"abc", "ABC")
    .str.replace(r"cde", "CDE")
    .str.replace(r"fgh", "FGH")
)

方式2:使用str.replace_all()配合映射字典(适合大量替换规则)

通过正则匹配所有需要替换的字符串,结合字典映射批量完成替换,效率更高:

import polars as pl 
df = pl.DataFrame({"id": [1, 2,3,4,5], "text": ["abc", "abc","cde","cde","fgh"]})
# 定义替换规则
replace_rules = {"abc": "ABC", "cde": "CDE", "fgh": "FGH"}
# 生成匹配任意目标字符串的正则模式
pattern = "|".join(replace_rules.keys())
# 批量替换
df2 = df.with_columns(
    pl.col("text").str.replace_all(pattern, lambda match: replace_rules[match.group(0)])
)

补充:生成多列不同替换结果

如果你的需求是生成多个分别对应不同替换规则的新列,需给每个表达式指定别名,并将所有表达式放入列表:

import polars as pl 
df = pl.DataFrame({"id": [1, 2,3,4,5], "text": ["abc", "abc","cde","cde","fgh"]})
df2 = df.with_columns([
    pl.col("text").str.replace(r"abc", "ABC").alias("text_abc_replaced"),
    pl.col("text").str.replace(r"cde", "CDE").alias("text_cde_replaced"),
    pl.col("text").str.replace(r"fgh", "FGH").alias("text_fgh_replaced")
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:43:12