Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between save a pandas dataframe to pickle and to csv?

I am learning python pandas. I see a tutorial which shows two ways to save a pandas dataframe.

  1. pd.to_csv('sub.csv') and to open pd.read_csv('sub.csv')

  2. pd.to_pickle('sub.pkl') and to open pd.read_pickle('sub.pkl')

The tutorial says to_pickle is to save the dataframe to disk. I am confused about this. Because when I use to_csv, I did see a csv file appears in the folder, which I assume is also save to disk right?

In general, why we want to save a dataframe using to_pickle rather than save it to csv or txt or other format?

like image 810
KevinKim Avatar asked Feb 13 '18 15:02

KevinKim


People also ask

What is the difference between pickle and CSV?

Pickle: Pickle is the native format of python that is popular for object serialization. The advantage of pickle is that it allows the python code to implement any type of enhancements. It is much faster when compared to CSV files and reduces the file size to almost half of CSV files using its compression techniques.

Is pickle file better than CSV?

Stop Using CSVs for Storage — Pickle is an 80 Times Faster Alternative.

When should I use CSV vs Pandas?

Pandas is better then csv for managing data and doing operations on the data. CSV doesn't provide you with the scientific data manipulation tools that Pandas does. If you are talking only about the part of reading the file it depends.


2 Answers

csv

  • ✅human readable
  • ✅cross platform
  • ⛔slower
  • ⛔more disk space
  • ⛔doesn't preserve types in some cases

pickle

  • ✅fast saving/loading
  • ✅less disk space
  • ⛔non human readable
  • ⛔python only

Also take a look at parquet format (to_parquet, read_parquet)

  • ✅fast saving/loading
  • ✅less disk space than pickle
  • ✅supported by many platforms
  • ⛔non human readable
like image 74
artoby Avatar answered Sep 21 '22 19:09

artoby


Pickle is a serialized way of storing a Pandas dataframe. Basically, you are writing down the exact representation of the dataframe to disk. This means the types of the columns are and the indices are the same. If you simply save a file as csv, you are just storing it as a comma separated list. Depending on your data set, some information will be lost when you load it back up.

You can read more about pickle library in python, here.

like image 45
Gabriel A Avatar answered Sep 21 '22 19:09

Gabriel A