read_sql to create Pandas DataFrame by using query from MySQL database table with options.

preview_player
Показать описание

0:00:01 Introduction to process of reading data from MySQL
0:00:25 Connection to MySQL database using SQLAlchemy
0:01:36 Query to read data from MySQL database table
0:02:14 Create Pandas DataFrame using Data from Mysql table
0:03.13 Parameter to pass using params option
0:05:34 index_col
0:06:07 columns option to collect given columns only.
0:7:46 Chunksize

WE will first connect to MySQL database by using SQLAlchemy connection engine. This connection string we will use in our further query execution.

Inside the SQLAlchemy connection string you can enter your MySQL login details like userid , password , host name , database name.
After connecting we will create the query to retrieve the rows.
We will use pandas sql_read() method to execute query by using SQL and connection string.
import pandas as pd
from sqlalchemy import create_engine
query="SELECT * FROM student WHERE class='Five'"
print(my_data)

Using params
We can pass parameters separately by using params query. This is to prevent injection attack.
query="SELECT * FROM student WHERE class=%s"
Using index_col
We can specify which column of the mysql database table can be used as index column in our created DataFrame.
chunksize
By using chunksize option we can specify number of records to retrieve as we get one iterator as output.
print(next(my_data))
print("----End of first set---")
print(next(my_data))

columns
We can specify the columns required from the table ( not query ) by suing a list or by tuple.
Рекомендации по теме
Комментарии
Автор

Hi,

Is it possible to convert below the input

Customer_Name, Product_1, Price_1, Product_2, Price_2
Zayn, Milk, 30, Chocolate, 40
Peter, Cheese, 190, Oil, 80
Andrew, Coconut, 10, Milk, 60
Dwayne, Soya, 100, Butter, 120

to this output where the Product name should be ascending and it should also have its price in the next column

Customer_Name, Product_1, Price_1, Product_2, Price_2
Zayn, Chocolate, 40, Milk, 30
Peter, Cheese, 190, Oil, 80
Andrew, Coconut, 10, Milk, 60
Dwayne, Butter, 120, Soya, 100


Can you please help

hayathbasha