📜  函数Pandas 中的 DataFrame.to_pickle()

📅  最后修改于: 2022-05-13 01:55:41.882000             🧑  作者: Mango

函数Pandas 中的 DataFrame.to_pickle()

to_pickle()方法用于将给定对象腌制(序列化)到文件中。此方法使用如下给出的语法:

句法:

DataFrame.to_pickle(self, path,
                    compression='infer',
                    protocol=4)
    Arguments                                                       Type   Description
     path            strFile path where the pickled object will be stored.
  compression                {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}                      A string representing the compression to use in the output file. By default, infers from the file extension in specified path.
 protocol             intInt which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible values are 0, 1, 2, 3, 4. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL.

示例 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 and printing
data = pd.DataFrame(dct)
print(data)
  
# using to_pickle function to form file 
# with name 'pickle_file'
data.to_pickle('pickle_file')


Python3
# importing packages
import pandas as pd
   
# dictionary of data
dct = {"f1": range(6), "b1": range(6, 12)}
   
# forming dataframe and printing
data = pd.DataFrame(dct)
print(data)
   
# using to_pickle function to form 
# file with name 'pickle_file'
data.to_pickle('pickle_file')


输出 :

ID     Name  Marks Grade
0  23      Ram     89     B
1  43     Deep     97     A
2  12     Yash     45     F
3  13     Aman     78     C
4  67    Arjun     56     E
5  89   Aditya     76     C
6  90    Divya    100     A
7  56  Chalsea     87     B
8  34    Akash     81     B

示例 2:

Python3

# importing packages
import pandas as pd
   
# dictionary of data
dct = {"f1": range(6), "b1": range(6, 12)}
   
# forming dataframe and printing
data = pd.DataFrame(dct)
print(data)
   
# using to_pickle function to form 
# file with name 'pickle_file'
data.to_pickle('pickle_file')

输出:

f1  b1
0   0   6
1   1   7
2   2   8
3   3   9
4   4  10
5   5  11