将HDF5转换为Parquet而不加载到内存中

时间:2017-09-11 14:08:45

标签: python pandas hdf5 parquet hdf

我有一个以HDF5格式存储的大型数据集(~600 GB)。由于它太大而无法放入内存中,我想将其转换为Parquet格式并使用pySpark执行一些基本数据预处理(归一化,查找相关矩阵等)。但是,我不确定如何将整个数据集转换为Parquet而不将其加载到内存中。

我查看了这个要点:https://gist.github.com/jiffyclub/905bf5e8bf17ec59ab8f#file-hdf_to_parquet-py,但似乎整个数据集都被读入内存。

我想到的一件事是以块的形式读取HDF5文件并将其逐步保存到Parquet文件中:

test_store = pd.HDFStore('/path/to/myHDFfile.h5')
nrows = test_store.get_storer('df').nrows
chunksize = N
for i in range(nrows//chunksize + 1):
    # convert_to_Parquet() ...

但我找不到任何可以让我逐步建立Parquet文件的文档。任何进一步阅读的链接将不胜感激。

2 个答案:

答案 0 :(得分:11)

您可以使用pyarrow

import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq


def convert_hdf5_to_parquet(h5_file, parquet_file, chunksize=100000):

    stream = pd.read_hdf(h5_file, chunksize=chunksize)

    for i, chunk in enumerate(stream):
        print("Chunk {}".format(i))

        if i == 0:
            # Infer schema and open parquet file on first chunk
            parquet_schema = pa.Table.from_pandas(df=chunk).schema
            parquet_writer = pq.ParquetWriter(parquet_file, parquet_schema, compression='snappy')

        table = pa.Table.from_pandas(chunk, schema=parquet_schema)
        parquet_writer.write_table(table)

    parquet_writer.close()

答案 1 :(得分:1)

感谢您的回答,我尝试从CLI调用以下py脚本,但该脚本未显示任何错误,也无法看到转换后的镶木文件。

h5文件也不是空的。enter image description here

将熊猫作为pd导入 将pyarrow导入为pa 将pyarrow.parquet导入为pq

h5_file =“ C:\ Users ... \ tall.h5” parquet_file =“ C:\ Users ... \ my.parquet”

def convert_hdf5_to_parquet(h5_file,parquet_file,chunksize = 100000):

stream = pd.read_hdf(h5_file, chunksize=chunksize)

for i, chunk in enumerate(stream):
    print("Chunk {}".format(i))
    print(chunk.head())

    if i == 0:
        # Infer schema and open parquet file on first chunk
        parquet_schema = pa.Table.from_pandas(df=chunk).schema
        parquet_writer = pq.ParquetWriter(parquet_file, parquet_schema, compression='snappy')

    table = pa.Table.from_pandas(chunk, schema=parquet_schema)
    parquet_writer.write_table(table)
parquet_writer.close()