如何将PyArrow表转为pandas,且直接将字符串列转为string[pyarrow]类型
解决方案
方法1:使用use_arrow_dtype参数(推荐,PyArrow 15.0+ 及 pandas 2.0+适用)
直接在to_pandas调用中添加use_arrow_dtype=True参数,转换后的pandas列会直接使用string[pyarrow]类型:
import pyarrow as pa import pandas as pd tbl = pa.table({'a': ['foo', 'bar']}) df = tbl.to_pandas(use_arrow_dtype=True) # 验证数据类型 print(df.dtypes) # 输出: # a string[pyarrow] # dtype: object
方法2:自定义类型映射函数(兼容旧版本)
如果你的PyArrow或pandas版本较低,不支持use_arrow_dtype参数,可以通过types_mapper参数指定类型转换逻辑:
import pyarrow as pa import pandas as pd def arrow_to_pandas_dtype(arrow_dtype): if pa.types.is_string(arrow_dtype): return pd.ArrowDtype(pa.string()) # 其他类型保持默认转换规则 return None tbl = pa.table({'a': ['foo', 'bar']}) df = tbl.to_pandas(types_mapper=arrow_to_pandas_dtype) print(df.dtypes) # 输出: # a string[pyarrow] # dtype: object
以上两种方法均在to_pandas转换过程中完成类型映射,无需在转换后额外调用convert_dtypes。
内容的提问来源于stack exchange,提问作者ignoring_gravity
相关产品推荐
相关产品推荐

