LoginSignup
20
17

More than 5 years have passed since last update.

Parquet, CSV, Pandas DataFrameをPyArrow経由で相互変換する

Last updated at Posted at 2017-11-16

ローカルだけで列指向ファイルを扱うために PyArrow を使う。
オプション等は記載していないので必要に応じてドキュメントを読むこと。

インストール

$ pip install pandas pyarrow

事前準備

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

CSVからParquetへの変換

CSV -> DataFrame -> Arrow Table -> Parquet というフローで書き出す。

# CSV -> DataFrame
df = pd.read_csv('/path/to/file.csv')

# DataFrame -> Arrow Table
table = pa.Table.from_pandas(df)

# Arrow Table -> Parquet
pq.write_table(table, '/path/to/file.pq')

Parquetの読み出しとDataFrameへのロード

# Parquet -> Arrow Table
table2 = pq.read_table('/path/to/file.pq')

# Arrow Table -> DataFrame
df2 = table.to_pandas()

圧縮オプション

snappy, gzip, brotli, none が選択可能。デフォルトは snappy

# brotli で圧縮して出力
pq.write_table(table, '/path/to/file-brotli.pq', compression='brotli')

圧縮率の比較

データによりけりなのでなんともいえないが、テストデータのCSVファイル(21,196行)だと以下のような結果になった。

ファイルフォーマット 圧縮形式 サイズ(KB) 備考
CSV なし 3154 元データ
CSV zip 327 zipコマンドで圧縮しただけ
Parquet なし 811
Parquet Snappy 540 PyArrowのデフォルト
Parquet GZip 370
Parquet Brotli 345

Snappyは圧縮率を犠牲にして圧縮・展開速度を重視した形式で、Hadoop等の大規模データ基盤ではデファクトで活用されている形式であるが、ローカルPCだけでの利用を想定するならそこまで大規模なデータになることはないので、圧縮率重視のGZipやBrotliでもいい気がする。

参考

Using PyArrow with Pandas: https://arrow.apache.org/docs/python/pandas.html
Reading and Writing the Apache Parquet Format: https://arrow.apache.org/docs/python/parquet.html

20
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
17