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
Release: 2024-12-05 11:07:12
Original
817 people have browsed it

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template