Home >Database >Mysql Tutorial >How Can I Retrieve SQL Query Results as a Pandas DataFrame?
Retrieving SQL Query Results as Pandas Data Structure
To retrieve the results of an SQL query into a Pandas data structure, follow these steps:
1. Establish a Connection
Use sqlalchemy.create_engine() to connect to the database and create an engine object.
2. Execute the Query
Use connection.execute() to execute the SQL query and store the results in a variable.
3. Convert to Pandas DataFrame
a. Fetch all rows from the query result using resoverall.fetchall().
b. Create a Pandas DataFrame by passing the result to pandas.DataFrame.
c. Set the DataFrame column names using resoverall.keys().
Example Code:
import pandas as pd from sqlalchemy import create_engine engine = create_engine('mysql://DATABASE_ADDRESS') connection = engine.connect() query_result = connection.execute("SQL_QUERY") df = pd.DataFrame(query_result.fetchall()) df.columns = query_result.keys()
The above is the detailed content of How Can I Retrieve SQL Query Results as a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!