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

Polars数据帧处理:用Amount列值替换Stat0列中的$i

解决Polars中字符串替换引用另一列值的问题

问题场景

现有如下Polars数据帧:

import polars as pl

df = pl.DataFrame(
    {
        "ItemId": [15148, 15148, 24957],
        "SuffixFactor": [19200, 200, 24],
        "ItemRand": [254, -1, -44],
        "Stat0": ['+5 Defense', '+$i Might', '+9 Vitality'],
        "Amount": ['', '7', '']
    }
)

需求是:当Stat0列包含$i时,用Amount列的对应值替换该$i。尝试了以下代码但未生效:

df = df.with_columns(
    pl.col('Stat0').str.replace(r'\$i', pl.col('Amount'))
)

期望得到的结果数据帧:

result = pl.DataFrame(
    {
        "ItemId": [15148, 15148, 24957],
        "SuffixFactor": [19200, 200, 24],
        "ItemRand": [254, -1, -44],
        "Stat0": ['+5 Defense', '+7 Might', '+9 Vitality'],
        "Amount": ['', '7', '']
    }
)

输出表格:

shape: (3, 5)
┌────────┬──────────────┬──────────┬─────────────┬────────┐
│ ItemId ┆ SuffixFactor ┆ ItemRand ┆ Stat0       ┆ Amount │
│ ---    ┆ ---          ┆ ---      ┆ ---         ┆ ---    │
│ i64    ┆ i64          ┆ i64      ┆ str         ┆ str    │
╞════════╪══════════════╪══════════╪═════════════╪════════╡
│ 15148  ┆ 19200        ┆ 254      ┆ +5 Defense  ┆        │
│ 15148  ┆ 200          ┆ -1       ┆ +7 Might    ┆ 7      │
│ 24957  ┆ 24           ┆ -44      ┆ +9 Vitality ┆        │
└────────┴──────────────┴──────────┴─────────────┴────────┘

问题原因

你之前的代码未生效,是因为在部分旧版本Polars中,str.replace的第二个参数仅支持静态字符串,无法直接传入列表达式作为动态替换值。

解决方案

方法1:新版本Polars直接使用列表达式(推荐)

如果你的Polars版本≥0.19.0,str.replace已支持将列作为替换值,原代码逻辑正确,可直接运行:

df = df.with_columns(
    pl.col('Stat0').str.replace(r'\$i', pl.col('Amount'))
)

注意:\$i是正则表达式写法,用于匹配字面量$i(因为$在正则中是特殊字符,必须转义)。

方法2:兼容旧版本的逐行处理写法

若使用的Polars版本较低,可通过map_elements逐行处理每一行的Stat0和Amount列:

df = df.with_columns(
    pl.struct(['Stat0', 'Amount']).map_elements(
        lambda x: x['Stat0'].replace('$i', x['Amount']),
        return_dtype=pl.String
    ).alias('Stat0')
)

该方法通过构造结构体聚合两列,再逐行执行字符串替换逻辑,最终重命名为Stat0列。

验证结果

执行上述任一方法后,均可得到你期望的结果数据帧。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:06:21