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

使用PyArrow写入Parquet文件时指定UUID逻辑类型的方法

如何在PyArrow中为Parquet指定UUID逻辑类型

问题背景

用PyArrow自定义UUID类型时(代码如下),将包含该类型的表写入Parquet文件后,字段仅被识别为fixed_len_byte_array(16),而非Parquet原生的UUID逻辑类型,需要实现正确标记UUID逻辑类型的方案。

自定义UUID类型代码:

import pyarrow as pa
class UuidType(pa.PyExtensionType):
    def __init__(self):
        pa.PyExtensionType.__init__(self, pa.binary(16))
    def __reduce__(self):
        return UuidType, ()

解决方案

方法一:使用PyArrow原生UUID类型(推荐,PyArrow 15.0.0+)

从PyArrow 15.0.0版本开始,官方新增了原生的pa.uuid()类型,直接用该类型定义Schema,写入Parquet时会自动映射为UUID逻辑类型,无需额外处理。

示例代码:

from uuid import uuid4
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

# 生成测试用UUID字节数据
uuid_bytes = [u.bytes for u in [uuid4() for _ in range(100)]]
df = pd.DataFrame({'uuid_column': uuid_bytes})

# 用原生uuid类型定义Schema
schema = pa.schema([('uuid_column', pa.uuid())])
table = pa.Table.from_pandas(df, schema=schema)

# 写入Parquet文件
with pq.ParquetWriter('uuid_data.parquet', schema) as writer:
    writer.write_table(table)

验证:通过pq.ParquetFile或parquet-tools查看文件架构时,该字段会被识别为UUID逻辑类型。

方法二:手动添加Parquet逻辑类型元数据(兼容旧版本)

如果使用的PyArrow版本低于15.0.0,可以给fixed_len_byte_array(16)字段手动添加Parquet逻辑类型元数据,指定为UUID。

示例代码:

from uuid import uuid4
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

uuid_bytes = [u.bytes for u in [uuid4() for _ in range(100)]]
df = pd.DataFrame({'uuid_column': uuid_bytes})

# 定义字段时添加PARQUET逻辑类型元数据
uuid_field = pa.field(
    name='uuid_column',
    type=pa.binary(16),
    metadata={'PARQUET:logicalType': 'UUID'}
)
schema = pa.schema([uuid_field])
table = pa.Table.from_pandas(df, schema=schema)

# 写入Parquet文件
with pq.ParquetWriter('uuid_data.parquet', schema) as writer:
    writer.write_table(table)

验证:此方式写入的Parquet文件,字段会被正确标记为UUID逻辑类型,工具可正常识别。

说明

自定义的PyExtensionType本质是基于binary(16)的扩展类型,写入Parquet时默认只会保留基础类型信息,不会自动关联Parquet的UUID逻辑类型,因此需要通过上述两种方式显式处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 11:48:28