LoginSignup
22

More than 3 years have passed since last update.

pandas.read_csvで圧縮ファイルも読み込めちゃうの。とても便利!

Posted at

この前書いた内容の続きをちまちまとやっていて、最初につまずいていたのがgzip圧縮されたログファイルを読み込むところでした。

圧縮ファイルの読み込み

gzipモジュール使えばいいでしょ、ふふん簡単♪、とつまずく気配を感じていなかったのですが、これがどうにも読み込めない・・・もう、どんなエラーだったか忘れてしまったんだけれど、なぜだったんだろう?(もちろん、エラーメッセージで色々検索はしてみました)

う〜ん、と悩みつつ、なぜか、pandas.read_csvのリファレンスを眺めていました(なんで眺めていたのか分かりません)が、そしたら、なんと!compressionというオプションがあるではないですか!

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’
For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.

New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.

オプションをきちんと読んでびっくり〜、キミは圧縮ファイルも空気読んで読み込んでくれる子だったのかー!

import pandas as pd
df = pd.read_csv('gzipで圧縮されたファイル.gz', sep='\t', header=None)

デフォルトだとcompression = 'infer'となっていて、ファイルの拡張子をみていい感じに判断してくれるそう。なので、read_csvの引数には明示しなくても大丈夫なはずです。

ただし、実行してみたら読み込みエラーが出たのでsep='\t'を指定。また、読み込んだログの1行目がデータフレームの列見出しになってしまったのでheader=Noneも指定しました。

圧縮ファイルの書き出し

圧縮ファイルを読み込めるならば、圧縮ファイルを書き出しできるのではと思って、pandas.DataFrame.to_csvもきちんと読んでみました。そしたら、やっぱり、compressionオプションがありました。

compression : str, default ‘infer’
Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. If ‘infer’ and path_or_buf is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’ or ‘.xz’. (otherwise no compression).
Changed in version 0.24.0: ‘infer’ option added and set to default.

お〜、キミも空気読んで圧縮形式を選んでくれるんですね!

df.to_csv('gzip圧縮したいファイル.gz', index=False, compression='gzip')

CSV形式で書き出す時に、pandas.DataFrameのインデックスは不要なのでindex=Falseにする。あと、たまに空気を読めていない時があったのでcompressionは明示することにしました。

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
22