We can create Python dictionary by using data from Pandas DataFrame. We will first create one Pandas DataFrame by using some sample data.
https://www.plus2net.com/python/panda...
import pandas as pd
df=pd.DataFrame(data={'id': [1, 2, 3],
'name': ['John Deo', 'Max Ruin', 'Arnold'],
'class': ['Four', 'Three', 'Three'],
'mark': [75, 85, 55],
'gender': ['female', 'male', 'male']})
my_dict=df.to_dict()
print(my_dict)
After creating the DataFrame we used to_dict() to create one dictionary
df.to_dict()
We can add different options to orientation while generating the dictionary. This option orient can take values like list, dict( default ) , series, split, record , index.
df.to_dict(orient=’list’)
From MySQL database using read_sql()
We can connect to MySQL database by using SQLAlchemy engine and after connection we will create our DataFrame by using data from sample table by using read_sql.
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
sql="SELECT * FROM student LIMIT 0,10"
df=pd.read_sql(sql,my_conn)
my_dict=df.to_dict()
Here 10 rows of data from the student table is taken and displayed as dictionary .
Excel or CSV file to string
From excel file we can create string by first creating the dataframe by reading the excel file by using the method read_excel()
df=pd.read_excel("D:\\my_data\\student.xlsx")
df.to_dict()
Similarly we can read csv file and generate JSON string
df=pd.read_csv("D:\\my_data\\student.csv")
df.to_dict()
#pandas_to_dict #dataframetodict #pandasdict #plus2net #pandas #datascience #pandastutorials