當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python DataFrame.read_pickle()用法及代碼示例


先決條件: pd.to_pickle method()

read_pickle()方法用於將給定的對象醃製(序列化)到文件中。此方法使用以下語法:

用法:

pd.read_pickle(path, compression='infer')

參數:

參數 類型 描述
path str 加載醃製對象的文件路徑。
compression {‘infer’,‘gzip’,“ bz2”,‘zip’,‘xz’,無},默認值為‘infer’ 對於on-the-fly,對on-disk數據進行解壓縮。如果為‘infer’,則如果路徑分別以“ .gz”,“。bz2”,“。xz”或“ .zip”結尾,則使用gzip,bz2,xz或zip,否則不進行解壓縮。設置為無不解壓。

下麵是上述方法的實現和一些示例:



範例1:

Python3

# importing packages  
import pandas as pd  
  
# dictionary of data  
dct = {'ID':{0:23, 1:43, 2:12,  
            3:13, 4:67, 5:89,  
            6:90, 7:56, 8:34},  
    'Name':{0:'Ram', 1:'Deep',  
                2:'Yash', 3:'Aman',  
                4:'Arjun', 5:'Aditya',  
                6:'Divya', 7:'Chalsea',  
                8:'Akash' },  
    'Marks':{0:89, 1:97, 2:45, 3:78,  
                4:56, 5:76, 6:100, 7:87,  
                8:81},  
    'Grade':{0:'B', 1:'A', 2:'F', 3:'C',  
                4:'E', 5:'C', 6:'A', 7:'B',  
                8:'B'}  
    }  
  
# forming dataframe  
data = pd.DataFrame(dct)  
  
# using to_pickle function to form file  
# with name 'pickle_file'  
pd.to_pickle(data,'./pickle_file.pkl') 
  
# unpickled the data by using the 
# pd.read_pickle method 
unpickled_data = pd.read_pickle("./pickle_file.pkl") 
print(unpickled_data)

輸出:

範例2:

Python3

# importing packages  
import pandas as pd  
  
# dictionary of data  
dct = {"f1":range(6), "b1":range(6, 12)}  
  
# forming dataframe  
data = pd.DataFrame(dct)  
  
# using to_pickle function to form file  
# with name 'pickle_data'  
pd.to_pickle(data,'./pickle_data.pkl') 
  
# unpickled the data by using the 
# pd.read_pickle method 
unpickled_data = pd.read_pickle("./pickle_data.pkl") 
print(unpickled_data)

輸出:





注:本文由純淨天空篩選整理自 DataFrame.read_pickle() method in Pandas。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。