17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

read_csvが遅い時対策

Posted at

こんにちは!
新米データサイエンティストのぽむです。

今日、会社で10GBくらいのcsvファイルをpandasで読み込もうとしました。
しかし、待てど暮らせど読み込みが終わらない...
これではお仕事にならないので、読み込み速度を速める方法を調べました。共有します!

①dtype引数の指定

read_csvにはdtypeを指定する引数があります。
例えば、下記のコードのようにカラムごとに設定できます。

import pandas as pd
pd.read_csv(file_path, dtype={"カラム名1": float, "カラム名2": int})

これをやるだけで、30分以上かかっていた読み込みが2分になりました🤗

②読み込みたいカラムだけを指定する

csvファイルの中身を見ると、分析には使えないカラムもたくさんありました。
そこでread_csvのusecols引数で読み込みたいカラムだけを指定しました。

import pandas as pd
pd.read_csv(file_path, usecols=["カラム名1", "カラム名2"])

これも少し早くなりました。また、読み込み速度だけではなくてメモリの節約にもなってお得です!

おわりに

他にもDaskというライブラリを使うととても速いみたいですが、難しそうなのでまた今度調べます!

ありがとうございました!

17
9
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
17
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?