用Python编写程序以将给定的数据帧导出为Pickle文件格式,并从Pickle文件中读取内容

假设您有一个数据框和导出到pickle文件的结果,并以如下方式从文件中读取内容:

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

解决方案

为了解决这个问题,我们将遵循以下步骤-

  • 定义一个数据框。

  • 将数据框导出为pickle格式,并将其命名为“ pandas.pickle”,

df.to_pickle('pandas.pickle')

  • 从“ pandas.pickle”文件中读取内容并将其存储为结果,

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

例子

让我们看一下下面的实现以更好地理解,

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)

输出

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

猜你喜欢