parquet - 如何使用 pyarrow 更改列数据类型
问题描述
我正在阅读一组箭头文件并将它们写入镶木地板文件:
import pathlib
from pyarrow import parquet as pq
from pyarrow import feather
import pyarrow as pa
base_path = pathlib.Path('../mydata')
fields = [
pa.field('value', pa.int64()),
pa.field('code', pa.dictionary(pa.int32(), pa.uint64(), ordered=False)),
]
schema = pa.schema(fields)
with pq.ParquetWriter('sample.parquet', schema) as pqwriter:
for file_path in base_path.glob('*.arrow'):
table = feather.read_table(file_path)
pqwriter.write_table(table)
我的问题是code
箭头文件中的字段是用int8
索引而不是int32
. 然而,范围int8
是不够的。因此,我为parquet 文件中的字段定义了一个带有int32
索引的模式。code
但是,现在将箭头表写入 parquet 会抱怨模式不匹配。
如何更改箭头列的数据类型?我检查了 pyarrow API,但没有找到更改架构的方法。这可以在不往返熊猫的情况下完成吗?
解决方案
Arrow ChunkedArray 有一个强制转换功能,但不幸的是它不适用于您想要做的事情:
>>> table['code'].cast(pa.dictionary(pa.int32(), pa.uint64(), ordered=False))
Unsupported cast from dictionary<values=uint64, indices=int8, ordered=0> to dictionary<values=uint64, indices=int32, ordered=0> (no available cast function for target type)
相反,您可以转换为pa.uint64()
并将其编码为字典:
>>> table['code'].cast(pa.uint64()).dictionary_encode().type
DictionaryType(dictionary<values=uint64, indices=int32, ordered=0>)
这是一个自包含的示例:
import pyarrow as pa
source_schema = pa.schema([
pa.field('value', pa.int64()),
pa.field('code', pa.dictionary(pa.int8(), pa.uint64(), ordered=False)),
])
source_table = pa.Table.from_arrays([
pa.array([1, 2, 3], pa.int64()),
pa.array([1, 2, 1000], pa.dictionary(pa.int8(), pa.uint64(), ordered=False)),
], schema=source_schema)
destination_schema = pa.schema([
pa.field('value', pa.int64()),
pa.field('code', pa.dictionary(pa.int32(), pa.uint64(), ordered=False)),
])
destination_data = pa.Table.from_arrays([
source_table['value'],
source_table['code'].cast(pa.uint64()).dictionary_encode(),
], schema=destination_schema)
推荐阅读
- assembly - 无法使用 nasm 编译具有 xmmword 操作数大小的汇编代码
- for-loop - 使用步骤 1 在 0 到 5 的向量中创建所有可能的组合?
- html - 聊天框 html-css 不关注最近的消息
- python - Colab 上没有名为“tensorflow.compat.v2”的模块
- algorithm - 距离和时基计算
- node.js - 电子商务应用使用 Node.js 和 MySQL Sequelize 生成 pdf 发票
- vbscript - 在 VBScript/JScript 中为控制台应用程序编写代理启动器
- mysql - MYSQL 插入缺少日期的行
- java - Spring Boot oauth2 配置中的多个客户端凭据-动态使用
- javascript - 编辑表单在提交时不会更改 - 仅在硬刷新时