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

如何在大型Polars多列数据框中替换大于9999的整数为"10K+"?

解决Polars DataFrame替换大于9999的值为"10K+"的问题

你的错误原因

Polars与Pandas的API不兼容,你使用的几个方法均为Pandas专属:

  • df.map:Polars DataFrame没有该方法,仅Series支持map操作
  • df.apply:Polars的apply是列级操作,lambda接收的是整个Series而非单个元素,直接与整数比较会触发类型错误
  • df.applymap:这是Pandas的逐元素处理方法,Polars不支持

正确解决方案

Polars推荐用向量化操作处理大型数据,效率远高于逐元素迭代。以下是两种可靠方法:

方法1:批量处理所有列(推荐)

通过with_columns结合Polars表达式,一次性处理所有列,自动将数值转为字符串并替换目标值:

import polars as pl

# 替换所有列中>9999的值为"10K+",并统一转为字符串类型
df = df.with_columns(
    pl.all().map_batches(
        lambda s: pl.when(s > 9999).then("10K+").otherwise(s.cast(pl.Utf8))
    )
)

方法2:仅处理整数类型列

如果只想替换整数列的数值,可先筛选出整数列再处理:

# 获取所有整数类型的列名(包含Int64/Int32/Int16)
int_columns = df.select(pl.col(pl.Int64, pl.Int32, pl.Int16)).columns

# 批量处理整数列
df = df.with_columns(
    [
        pl.when(pl.col(col) > 9999)
          .then("10K+")
          .otherwise(pl.col(col).cast(pl.Utf8))
          .alias(col)
        for col in int_columns
    ]
)

关键说明

  • 必须将列转为Utf8类型:Polars要求列内类型统一,替换后的"10K+"是字符串,因此需要把原本的数值列转为字符串类型
  • 向量化操作优势:针对大型数据集,map_batches和when/then/otherwise是批量处理,比逐元素的map_elements效率高得多

内容的提问来源于stack exchange,提问作者Stephen Beckstrom-Sternberg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:24:57