Blog Posts

Pandasql -The Best Way to Run SQL Queries in Python

Blog: Think Data Analytics Blog

Introduction

Pandas have come a long way on their own, and are considered second to none when it comes to data handling. Still, there are many SQL power users who consider SQL queries nothing less than sacred, and swear by them.

For such users and also for those who chase efficiency in coding (I do agree that SQL Queries are more efficient for some operations!), there is some good news. You can use the, as it is, to do data manipulation inside the python environment.

That too in Jupyter Notebooks. Not only that, you can query pandas DataFrame directly using only SQL queries or syntax. If it sounds much like a fantasy, tighten your seat belts and join me in this adventure to marry SQL with Pandas. And did I say, You do not need to install or connect any SQL servers 

The saviour is python’s library, pandasql.

As the libraries’ documentation mentions:

pandasql allows you to query pandas DataFrames using SQL syntax. It works similarly to sqldf in Rpandasql seeks to provide a more familiar way of manipulating and cleaning data for people new to Python or pandas.

Installation

You need to install the Python’s Library, pandasql first. It’s very simple to install. Use any of the below two methods, both use PIP installation.

Basics

There is this one function that is used the most from this library. Its the main function sqldfsqldf takes two parameters.

It becomes tedious to specify globals() or locals(), hence whenever you import the library, run the following helper function along with. This will make things simple going forward.

from pandasql import sqldf 
mysql = lambda q: sqldf(q, globals())

Syntax

There are many variants of SQL in use, and their syntaxes vary a little. Here in pandasql uses the SQLite syntax. Most of the standard SQL language SQLite understands. However, it adds few features of its own while at the same time it does omit some features. Click Here to read the document that attempts to describe what parts of the SQL language SQLite do and do not support.

pandasql automatically detects any pandas DataFrame. You can call them or query them by their name in the same way you would have done with a SQL table.

We are going to use any one of these two basic code samples.

from pandasql import sqldf

or

from pandasql import sqldf

Import libraries and Data

For this article, we are going to use the data from the pandasql library itself. Let us import the dependencies and the data.In [1]:

import pandas as pd
from pandasql import sqldf
from pandasql import load_meat, load_births          # Importing Data
​# Bring data in Python environment as pandas DataFrame
​meat = load_meat()
births = load_births()

Let us have a look at the Data.In [2]:

meat.head()

Out[2]:

In [3]:

births.head()Out[3]:

Read Data using SQL Query

We will read the first 5 rows of data, for the meat and births data frames using SQL. The result shall be similar to what we get from using .head()In [4]:

# specify globals() or locals() using the following helper function
​mysql = lambda q: sqldf(q, globals())
mysql("SELECT * FROM meat LIMIT 5;")

Out[4]:

In [5]:

mysql("SELECT * FROM births LIMIT 5;")

Out[5]:

Join (or merge) DataFrames using SQL Queries

Joining tables is one of the most common tasks being performed by SQL. Understandably so, as the relational databases have data segregated in separate tables. Hence, SQL users are pretty used to using join() tables in SQL. We can use the power of SQL JOIN here with pandas DataFrame.In [6]:

query = '''
SELECT m.date, m.beef, m.veal, m.pork, b.births
FROM meat AS m
INNER JOIN
births AS b
ON m.date = b.date;
'''
​
mysql(query)

Out[6]:

407 rows × 5 columns

GROUP BY using SQL

The data of meat production is month-wise. We want to see the beef production per year. For that we need to groupby() and aggregate. We can do this using the SQL GROUP BY function.In [7]:

query = '''SELECT
            strftime('%Y', date) as year
           , SUM(beef) as beef_total
           FROM
              meat
           GROUP BY
              year
              LIMIT 5;
    '''
​
mysql(query)

Out[7]:

In the above code, we used SQL query to limit the number of rows for the grouped and aggregated table to 5 rows. But the output and the input, both are not SQL tables. They are pandas DataFrames. And this gives us the liberty to use Pandas functions and methods on the same.

Let us do the same operation, and this time the output shall be the first 10 rows. But the SQL query will give a full table and we will use pandas head() function to get the final output truncated to 10 rows.In [8]:

query = '''SELECT
            strftime('%Y', date) as year
           , SUM(beef) as beef_total
           FROM
              meat
           GROUP BY
              year;
    '''
​
mysql(query).head(10)

Out[8]:

UNION ALL to club multiple variables in SQL

We have beef, pork, and veal as meat types, in separate columns. Here we want all the production values in one column and the identifier in another column. We can use UNION ALL function from SQL to achieve this easily.In [9]:

#executing union all statements
query = """
        SELECT
            date
            , 'beef' AS meat_type
            , beef AS value
        FROM meat
        UNION ALL
        SELECT
            date
            , 'veal' AS meat_type
            , veal AS value
        FROM meat
        UNION ALL
        SELECT
            date
            , 'pork' AS meat_type
            , pork AS value
        FROM meat
        UNION ALL
        SELECT
            date
            , 'lamb_and_mutton' AS meat_type
            , lamb_and_mutton AS value
        FROM meat
        ORDER BY 1
    """
​
mysql(query).head(10)

Out[9]:

Nested Queries of SQL

In SQL, writing queries within another query is commonplace. The same kind of nesting of queries is possible here as well. We will create one table (or say DataFrame) and without assigning it any variable (or name), we will use that to create another table.In [10]:

# use queries within queries
query = """
    SELECT
        m1.date
        , m1.beef
    FROM
        meat m1
    WHERE m1.date IN
        (SELECT
            date
        FROM meat
        WHERE
            beef >= broilers
        ORDER BY date)
"""
​
mysql(query)

Out[10]:

421 rows × 2 columns

Conclusion:

In this article, we saw that how easily we can use SQL queries to operate upon the DataFrames. This gives us a unique opportunity. This weapon can be a potent one in any Data Scientist’s arsenal, who knows SQL and Python, both.

They both are powerful languages and have their respective strengths and weaknesses. Using the method shown in this article, or in other words, using the pandasql library and sqldf function, we can use the best and most efficient method to manipulate data, well within the python environment and even Jupyter Notebook. This is music to my ears. I hope you enjoyed the song too .

In this article, you saw how to use SQL queries inside python. But if you want to connect the two most powerful workhorses of the Data Science world, SQL and Python. This is not the end, but only the first step towards getting the “Best of Both Worlds”.

End Notes

Now you can start using Python to work upon your data which rests in SQL Databases. In able to connect to your SQL databases, go thru my article How to Access & Use SQL Database with pyodbc in Python. Once you brought it as DataFrame, then all the operations are usual Pandas operations or SQL queries being operated on Pandas DataFrame as you saw in this article.

Apart from the function of SQL shown in this article, many other popular SQL functions are easily implementable in Python. Read 15 Pandas functions to replicate basic SQL Queries in Python for learning how to do that.

The implied learning in this article was, that you can use Python to do things that you thought were only possible using SQL. There may or may not be straight forward solution to things, but if you are inclined to find it, there are enough resources at your disposal to find a way out. You can look at the mix and match the learning from my book, PYTHON MADE EASY – Step by Step Guide to Programming and Data Analysis using Python for Beginners and Intermediate Level.

About the Author: I am Nilabh Nishchhal. I like making seemingly difficult topics easy and write about them. Check out more at https://www.authornilabh.com/. My attempt to make Python easy and Accessible to all is Python Made Easy.

Cover Photo Credit: Photo by Norbert Hentges on Unsplash

Original

The post Pandasql -The Best Way to Run SQL Queries in Python appeared first on ThinkDataAnalytics.

Leave a Comment

Get the BPI Web Feed

Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

Copy/Paste this code in your website html code:

<iframe src="https://www.businessprocessincubator.com/content/pandasql-the-best-way-to-run-sql-queries-in-python/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

Customizing your BPI Web Feed

You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

Customizing the Content Filter
On any page, you can add filter criteria using the MORE FILTERS interface:

Customizing the Content Filter

Customizing the Content Sorting
Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

Get the BPI Web Feed

Some integration examples

BPMN.org

XPDL.org

×