How to Write a Pandas DataFrame to a Pickle File?

Spread the love

To write a Pandas DataFrame to a Pickle file we use the to_pickle() method in Pandas.

Syntax –

DataFrame.to_pickle(self, path, compression='infer', protocol=4)

Parameters –

  • path – File path where the pickled object will be stored.
  • compression – A string representing the compression to use in the output file. By default, infers from the file extension in specified path. options – {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None} Default Value: ‘infer’.
  • protocol – Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL.

Examples –

Let’s read a dataset in pandas.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv'
df = pd.read_csv(url)
df.head()

Now, we can write this dataframe to a pickle file using the to_pickle() method in pandas.

# write to a pickle file
df.to_pickle('clothing_store_sales.pkl')

Related Posts –

  1. How to Read a Pickle file in Pandas?

Rating: 1 out of 5.

Leave a Reply