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

Polars from_pandas()报错:字典仅支持类字符串值,如何解决?

解决Pandas分类列(int/float类型)转Polars DataFrame的报错问题

当Pandas DataFrame中包含整数或浮点数类型的分类列时,直接使用pl.from_pandas()转换为Polars DataFrame会触发如下错误:

ComputeError: only string-like values are supported in dictionaries

示例代码:

import pandas as pd
import polars as pl

df = pd.DataFrame(
    {
        "label1": pd.Categorical([1, 1, 1, 2, 2]),
        "label2": pd.Categorical([0.5, 0.4, 0.3, 0.4, 0.3]),
        "measurement": [1, 2, 3, 4, 5],
    }
)

# 执行此代码会报错
pl_df = pl.from_pandas(df)

以下是几种可行的规避方案:

  • 方案1:将分类列的类别转为字符串类型
    Polars的字典(对应Pandas分类)类型仅支持字符串类别的键,因此可以先将Pandas分类列的类别重命名为字符串,再进行转换:
# 遍历所有分类列,将类别转为字符串
for col in df.select_dtypes('category').columns:
    df[col] = df[col].cat.rename_categories(str)

pl_df = pl.from_pandas(df)
  • 方案2:转换为普通数值列(放弃分类类型)
    如果业务场景不需要保留分类类型,可以直接将分类列转为对应的数值类型:
# 转换分类列为数值类型
df['label1'] = df['label1'].astype(int)
df['label2'] = df['label2'].astype(float)

pl_df = pl.from_pandas(df)
  • 方案3:手动构建Polars分类列
    若需要保留分类类型,可手动创建Polars的pl.Categorical列,显式将类别转为字符串:
pl_df = pl.DataFrame({
    "label1": pl.Categorical(df['label1'].astype(str)),
    "label2": pl.Categorical(df['label2'].astype(str)),
    "measurement": df['measurement']
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:44:51