path ( file ) | Path with file name to store the byte string of pickled data |
compression | (Optional )Type of compression, {'infer', 'gzip', 'bz2', 'zip', 'xz', None} |
protocol | (Optional) , Int, we can use HIGHEST_PROTOCOL to get the latest |
We can create a file with DataFrame data by using to_pickle(). We will create one DataFrame by using a dictionary.
import pandas as pd
import pickle
my_dict={
'NAME':['Ravi','Raju','Alex'],
'ID':[1,2,3],'MATH':[30,40,50],
'ENGLISH':[20,30,40]
}
df = pd.DataFrame(data=my_dict)
df.to_pickle("my_data.pkl") # pickled
This is the data written to the current directory. Check for the file my_data.pkl . You can use path to store the file in different location.
df.to_pickle("D:\my_data\my_data.pkl")
df.to_pickle("my_data.pkl",compression='zip')
df.to_pickle("my_data.pkl",protocol=pickle.HIGHEST_PROTOCOL)
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_db")
sql="SELECT * FROM student LIMIT 0,10 "
df = pd.read_sql(sql,my_conn)
df.to_pickle("D:\my_data\my_data.pkl")
df=pd.read_excel("D:\\my_data\\student.xlsx") # Path of the file.
df.to_pickle("D:\my_data\my_data.pkl")
We can read one csv file by using read_csv()
df=pd.read_csv("D:\\my_data\\student.csv") # change the path
df.to_pickle("D:\my_data\my_data.pkl")
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.