---
title: "10 Pandas SQL Queries to Use Frequently for Transformation"
description: "The content outlines similarities between SQL operations and Pandas data manipulation, including reading CSVs, filtering, sorting, and group operations."
url: https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/
date: 2023-09-10
modified: 2026-10-05
author: "Srini"
image: https://i0.wp.com/srinimf.com/wp-content/uploads/2023/09/pexels-photo-7267572.jpeg?fit=1880%2C1253&ssl=1
categories: ["Data Science"]
tags: ["Equivalent", "Pandas SQL Operations"]
type: post
lang: en
---

# 10 Pandas SQL Queries to Use Frequently for Transformation

Pandas makes it easy to search and filter data with DataFrame and Series. It has tools for changing data. Here are the Pandas SQL queries for Dataframes.

![Pandas SQL queries](https://i0.wp.com/srinimf.com/wp-content/uploads/2023/09/pexels-photo-5152692.jpeg?resize=1880%2C1253&ssl=1)*Photo by Carlos Montelara on Pexels.com*

Table of contents

1. [Reading CSV file and display all the columns](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#reading-csv-file-and-display-all-the-columns)
2. [Get specific columns](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#get-specific-columns)
3. [Filter rows on a condition](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#filter-rows-on-a-condition)
4. [Sort the result set](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#sort-the-result-set)
5. [Get unique values](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#get-unique-values)
6. [Group by rows by a specific column](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#group-by-rows-by-a-specific-column)
7. [Calculate average for each group](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#calculate-average-for-each-group)
8. [Count number of rows in each group](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#count-number-of-rows-in-each-group)
9. [Pandas to_sql](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#pandas-to-sql)
10. [Conclusion](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/#conclusion)

## Reading CSV file and display all the columns

```
#Pandas: Use the DataFrame directly.
import pandas as pd
df = pd.read_csv('your_data.csv') # Load your data into a DataFrame
display(df)

#Equivalent SQL query:
SELECT column1, column2 FROM table_name
```

## Get specific columns

```
#Pandas: Specify the column names as a list when indexing the DataFrame.
selected_columns = df[['column1', 'column2']]

#Equivalent SQL query:
SELECT * FROM table_name WHERE condition
```

## Filter rows on a condition

```
#Pandas: Use boolean indexing to filter rows based on a condition.
filtered_df = df[df['column_name'] > 10] # Example condition

#Equivalent SQL query:
SELECT * FROM table_name ORDER BY column_name ASC/DESC
```

## Sort the result set

```
#Pandas: Use the sort_values method.
sorted_df = df.sort_values(by='column_name', ascending=False)

#Equivalent SQL query:
SELECT DISTINCT column_name FROM table_name
```

## Get unique values

```
#Pandas: Use the unique method on a Series.
unique_values = df['column_name'].unique()

#Equivalent SQL query:
GROUP BY column_name
```

## Group by rows by a specific column

```
#Pandas: Use the groupby method.
grouped = df.groupby('column_name')

#Equivalent SQL query:
SELECT AVG(column_name) FROM table_name GROUP BY column_name
```

## Calculate average for each group

```
#Pandas: Use the groupby and agg functions.
avg_by_group = df.groupby('column_name')['other_column'].agg('mean')

#Equivalent SQL query:
SELECT uid, result, AVG(value) AS v_1 
FROM data
GROUP BY uid, result;
```

## Count number of rows in each group

```
# Pandas: Use the groupby and size functions.
count_by_group = df.groupby('column_name').size()

#Equivalent SQL query:
SELECT COUNT(*) FROM table_name GROUP BY column_name
```

## Pandas to_sql

Here’s an example of using `pandas` to write a DataFrame to a SQL database table.

```
import pandas as pd
from sqlalchemy import create_engine

# Create a sample DataFrame
data = {'Name': ['John', 'Alice', 'Bob'],
        'Age': [28, 32, 45],
        'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)

# Create a SQLite database engine
engine = create_engine('sqlite:///sample.db')

# Write the DataFrame to a SQL table
df.to_sql('persons', con=engine, if_exists='replace', index=False)

# Query the newly created table
result = pd.read_sql('SELECT * FROM persons', con=engine)
print(result)
```

Output

```
Name  Age      City
0   John   28  New York
1  Alice   32     Paris
2    Bob   45    London
```

In this example, we first create a DataFrame `df` with sample data. Then, we create a SQLite database engine using the `create_engine` function and specify the database connection URL. Next, we use the `to_sql` method of the DataFrame to write the data to a table named ‘persons’ in the database specified by the engine. The `if_exists` parameter is set to ‘replace’ to replace the table if it already exists. Finally, we use `pd.read_sql` to query the ‘persons’ table and print the result.

## Conclusion

Pandas is a powerful and flexible tool in Python for data manipulation and analysis. It provides numerous functionalities beyond the covered SQL operations.

### Share this:

-
- [Tweet](https://twitter.com/share)
- [![](https://i0.wp.com/assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png)](https://www.pinterest.com/pin/create/link/?url=https%3A%2F%2Fsrinimf.com%2F2023%2F09%2F10%2Fhow-to-practice-sql-in-pandas-8-best-examples%2F&media=https%3A%2F%2Fi0.wp.com%2Fsrinimf.com%2Fwp-content%2Fuploads%2F2023%2F09%2Fpexels-photo-7267572.jpeg%3Ffit%3D1200%252C800%26ssl%3D1&description=10%20Pandas%20SQL%20Queries%20to%20Use%20Frequently%20for%20Transformation)
-
- [Share on Tumblr](https://www.tumblr.com/share)
- [Share on WhatsApp (Opens in new window) WhatsApp](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/?share=jetpack-whatsapp)
- [More](#)
-

- [Print (Opens in new window) Print](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/?share=print)
- [Share on Reddit (Opens in new window) Reddit](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/?share=reddit)
- [Share on Telegram (Opens in new window) Telegram](https://srinimf.com/2023/09/10/how-to-practice-sql-in-pandas-8-best-examples/?share=telegram)
- [Email a link to a friend (Opens in new window) Email](mailto:?subject=%5BShared%20Post%5D%2010%20Pandas%20SQL%20Queries%20to%20Use%20Frequently%20for%20Transformation&body=https%3A%2F%2Fsrinimf.com%2F2023%2F09%2F10%2Fhow-to-practice-sql-in-pandas-8-best-examples%2F&share=email)
-

### Like this:

Like Loading…
