Computer >> Computer tutorials >  >> Programming >> Python

Write a program in Python to export a given dataframe into Pickle file format and read the content from the Pickle file


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