Home >Database >Mysql Tutorial >How Can I Retrieve SQL Query Results as a Pandas DataFrame?

How Can I Retrieve SQL Query Results as a Pandas DataFrame?

DDD
DDDOriginal
2024-12-05 11:07:12804browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn