用 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
广告