如何在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>)
常见错误原因说明
dictionary[pyarrow]不被识别:Dictionary类型需要额外的索引/值类型参数,无法像string[pyarrow]那样用简单字符串格式声明。categorical[pyarrow]/category[pyarrow]无效:Pandas的Categorical类型与PyArrow的Dictionary类型逻辑相似但实现不同,需明确使用Arrow的Dictionary定义。- 直接传入
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
相关产品推荐
相关产品推荐

