如何使用pyarrow在HDFS上写入

How to write on HDFS using pyarrow

我正在使用 python 和 pyarrow 库,我想在 HDFS 上写一个 pandas 数据帧。这是我的代码

import pandas as pd
import pyarrow as pa

fs = pa.hdfs.connect(namenode, port, username, kerb_ticket)
df = pd.DataFrame(...)
table = pa.Table.from_pandas(df)

根据文档,我应该使用以下代码在 HDFS

上编写 pyarrow.Table
import pyarrow.parquet as pq
pq.write_parquet(table, 'filename.parquet')

我不明白的是我应该在哪里使用我的连接 (fs),因为如果我不在 write_parquet 中使用它那么它怎么知道 HDFS 在哪里?

你可以做到

with fs.open(path, 'wb') as f:
   pq.write_parquet(table, f)

我打开了一个关于添加更多关于此的文档的 JIRA

https://issues.apache.org/jira/browse/ARROW-6239

基于文档:https://arrow.apache.org/docs/python/api/formats.html#parquet-files

您可以使用 write_table 或 write_to_dataset 函数:

write_table

write_table 接受多个参数,其中一些参数如下:

table -> pyarrow.Table
where -> this can be a string or the filesystem object
filesystem -> Default is None

例子

pq.write_table(table, path, filesystem = fs)

with fs.open(path, 'wb') as f:
    pq.write_table(table, f)

write_to_dataset

如果您想根据 table 中的特定列对数据进行分区,您可以使用 write_to_dataset,示例:

pq.write_to_dataset(table, path, filesystem = fs, partition_cols = [col1])