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

如何在Pandas中使用PyArrow Dictionary类型处理分类数据?

在Pandas中使用PyArrow Dictionary dtype的正确方式

要在Pandas Series或DataFrame中实现PyArrow的Dictionary类型(对应分类逻辑),不能直接使用字符串格式的dictionary[pyarrow],需通过以下步骤正确定义:

  • 明确PyArrow Dictionary的类型参数:Arrow的Dictionary类型是强类型,必须指定索引的整数类型(如pyarrow.int16())和值的类型(如pyarrow.string())。
  • 用pd.ArrowDtype包装类型:将定义好的PyArrow Dictionary类型传入pd.ArrowDtype,作为Series/DataFrame的dtype参数。

示例代码

import pandas as pd
import pyarrow as pa

# 定义PyArrow Dictionary类型:int16索引 + string值
dict_dtype = pa.dictionary(pa.int16(), pa.string())

# 创建带有该类型的Series
s = pd.Series(['Chocolate','Candy','Waffles'], dtype=pd.ArrowDtype(dict_dtype))

# 验证类型
print(s.dtype)
# 输出:ArrowDtype(dictionary<values=string, indices=int16, ordered=0>)

常见错误原因说明

  1. dictionary[pyarrow]不被识别:Dictionary类型需要额外的索引/值类型参数,无法像string[pyarrow]那样用简单字符串格式声明。
  2. categorical[pyarrow]/category[pyarrow]无效:Pandas的Categorical类型与PyArrow的Dictionary类型逻辑相似但实现不同,需明确使用Arrow的Dictionary定义。
  3. 直接传入pyarrow.dictionary(...)失败:Pandas需要通过pd.ArrowDtype包装PyArrow类型,才能正确识别为Arrow-backed的dtype。

DataFrame中指定类型的示例

df = pd.DataFrame(
    {'food': ['Chocolate','Candy','Waffles','Candy']},
    dtype={'food': pd.ArrowDtype(pa.dictionary(pa.int16(), pa.string()))}
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 14:17:20