Home >Database >Mysql Tutorial >How to Convert SQL Query Results into a Pandas DataFrame?

How to Convert SQL Query Results into a Pandas DataFrame?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 19:42:17301browse

How to Convert SQL Query Results into a Pandas DataFrame?

Converting SQL Query Results to pandas DataFrames

In this scenario, you aim to retrieve data from an SQL database using a query and store it in a pandas data structure. The question revolves around the data type of the query result and how to convert it to a DataFrame.

Understanding the Query Result

The sample query you provided performs various summations on fields from the table "daily_report_cooked." The result is a collection of rows, each containing the aggregate values for a particular campaign.

Converting to a pandas DataFrame

To convert the query result to a DataFrame, follow these steps:

  1. Create a pandas DataFrame: Construct an empty DataFrame using the DataFrame class without any arguments.
  2. Fetch the query results: Use the fetchall() method of the resoverall object to obtain a list of tuples representing the rows of the query result.
  3. Populate the DataFrame: Assign the list of tuples to the DataFrame's data property.
  4. Set column names: Retrieve the column names from the resoverall object using the keys() method, and assign them to the DataFrame's columns property.

The following code snippet demonstrates the conversion process:

from pandas import DataFrame
df = DataFrame(resoverall.fetchall())
df.columns = resoverall.keys()

Now, the variable df represents a pandas DataFrame containing the query results. It provides a structured representation of the data, enabling further analysis and manipulation using pandas' extensive functionality.

The above is the detailed content of How to Convert SQL Query Results into 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