Export DataFrame to Pickle File Format in Python



Assume you have a dataframe and the result for exporting into pickle file and read the contents from file as,

Export to pickle file:
Read contents from pickle file:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington

Solution

To solve this, we will follow the steps given below −

  • Define a dataframe.

  • Export the dataframe to pickle format and name it as ‘pandas.pickle’,

df.to_pickle('pandas.pickle')
  • Read the contents from ‘pandas.pickle’ file and store it as result,

result = pd.read_pickle('pandas.pickle')

Example

Let’s see the below implementation to get better understanding,

import pandas as pd
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
                     'City' : ["Shimla","Sydney","Lucknow","Wellington"]
                  })
print("Export to pickle file:")
df.to_pickle('pandas.pickle')
print("Read contents from pickle file:")
result = pd.read_pickle('pandas.pickle')
print(result)

Output

Export to pickle file:
Read contents from pickle file:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington
Updated on: 2021-02-24T10:31:34+05:30

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements