filmov
tv
Python Pandas DataFrame output as Dictionary & using MySQL sample table as source using to_dict()
Показать описание
We can create Python dictionary by using data from Pandas DataFrame. We will first create one Pandas DataFrame by using some sample data.
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']})
print(my_dict)
After creating the DataFrame we used to_dict() to create one dictionary
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.
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
sql="SELECT * FROM student LIMIT 0,10"
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()
Similarly we can read csv file and generate JSON string
#pandas_to_dict #dataframetodict #pandasdict #plus2net #pandas #datascience #pandastutorials
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']})
print(my_dict)
After creating the DataFrame we used to_dict() to create one dictionary
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.
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
sql="SELECT * FROM student LIMIT 0,10"
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()
Similarly we can read csv file and generate JSON string
#pandas_to_dict #dataframetodict #pandasdict #plus2net #pandas #datascience #pandastutorials
Комментарии