SQL Queries For Pandas DataFrames

NeuralNine · Beginner ·📊 Data Analytics & Business Intelligence ·3y ago

Key Takeaways

This video teaches how to use SQL statements to query data from Pandas DataFrames using the pandasql library, covering basic queries, filtering, and joining data frames.

Full Transcript

what is going on guys welcome back in today's video we're going to learn how to use SQL statements to query data from Panda's data frames so let us get right into it it's not a game it's a [Music] red all right so obviously for this video we're going to need pandas which is an external python module so we need to install it and in addition to that we're also going to need pandas ql which is basically pandas SQL but with only one s so pandas ql uh which is also an external python module so in order to install those two we open up a command line and we type pip install first of all pandas if you don't have it already and then pip install pandas ql to enable to allow us to do uh the SQL querying with pandas data frames and then what you need is you need some data frames so you can either uh use something like pandas data reader to get some financial data from the web you can create your own data frame by creating a dictionary parsing it into a data frame or you can import just some CSV file which is what I'm going to do so I have here this simple CSV file uh where I have the ID name age height gender of a bunch of artificial people here so we have one to eight for the ID we have a bunch of names here we have ages and Heights and then we have MF for male female um that is just some sample data you can create whatever data you want you can put it into a CSV file and then you just import it so the focus not going to be obviously on the data the focus is going to be on quarrying using SQL statements and for that we're going to start by importing pandas SPD which is the usual Alias and by importing pandas qls uh PS I'm not sure if that is like the uh the goto best practice Alias or if you would use an alias at all but we're just going to use PS for this video here and now we're going to say data equals PD read CSV and we're going to get the data. CSV file here and we're going to say data set _ index is going to be uh ID and we're going to assign that to data and then we're going to take a look at it by printing data to see if that works and now you can see we have name AG height gender as the columns here we have the ID column which is the index and this is basically what we have now and now we might want to find for example all persons all people that have an age above 30 for example now before we go into the SQL query in we're going to do a simple pandas query to see how it would work without SQL statement so what we can do here is we can say print data. query which is a pandas function without using pandas ql um and here we can just uh specify a string expression that uh is the query that we want to have for example we can say okay the age has to be above 30 and then what happens is we get only the entries where the age is above 30 so you see 1 3 5 5 68 Rd IDs where this is the case we can also of course say greater or equal to 30 and then we get uh I think an additional record here anna because the age of Anna is exactly 30 so this is how you do it without SQL and this is fine uh you can also do stuff like for example gender equals and then single quotations F to only get the women as you can see here so this works and this is the simple way to do it uh with pandas with only pandas now we can use pandas ql to do the same thing with SQL statements and for that what we can do is we can say uh print or actually let's first Define the SQL query in a statement here we can do something like select everything so select star from and um then essentially what we have to provide here is we have to provide the data uh the data frame so in the string we're going to say data and this name here has to be the same as this name here so this query will be used on this uh data frame here so the data frame will be treated as a table which it is essentially so this is a database table now we're going to say select everything from data where and then AG is greater than 30 for example and then what I can do now is I can say print PS SQL DF so ps. SQL DF and then we execute the SQL query um and we pass the local post function here as well and then you can see we have the exact same output so now the difference here is that we get now U uh again the ID as a column here so we have now a different index we could also just store the data frame set index to ID again and drop the index that we have here but essentially we get the entries that we're interested in and of course we can do the same thing here with uh for example gender equals uh I think we need to provide it here again in single quotation right there you go gender equals F uh and I think we should also be able to do end so age is above 30 I think this should work as well there you go we only have one entry left here so this works uh and we can do even more complicated stuff like for example let's say we have now uh data 2 which is going to be a second data frame we're going to just create it now from scratch we're going to say here the Pan's data frame of a given dictionary the dictionary is going to have an ID uh list and it's only going to have one ID in that list ID 2 and then we're going to say that we want to specify a job here and we want to say the jop list is just programmer so this is essentially just uh a data frame now we can actually print this data 2 let me just oh come on data 2 let's common this out here um this is now just a simple ID job data frame that we have here now we can take take this and merge it we can join it via an SQL statement to make an advanced query with panda ql so what I can do here now is I can go ahead and say the SQL query that I want to make is the following it is Select everything from data and I can also provide an alias like d so select everything from data D left join um and then I can say data 2 D2 is D alas now on D ID is the same as D2 doid and of course you can play around with more details you can make it more professional everything but we can now go ahead and say print ps. uh SQL DF sqlquery and then locals again and then you will be able to see that we have now ignore the first column here but that we have here now um Anna which is id2 and she now has a job all the others do not have a job this is because we did a left join which means that we keep all the entries even though the job is none for all of them um we could also drop this second ID column here but essentially uh since we joined on the ID we now have for Anna which is which has the same ID here the drop programmer this is just some very basic example but that is how you do it this is how you can use SQL queries to get data from data frames and you get a resulting data frame from from that so you can get uh a smaller version of the data frame uh where certain conditions are met you can do joints you can do a lot of things you cannot do everything I think stuff like uh I tried to do I think a full outer joint and I think the error message set it's not supported as far as I remember there you go um what was it write and full outter joints are not currently supported so you have some limitations here but essentially this is how you can do it in Python so that's it for today's video I hope you enjoyed it and I hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you in the next video and bye [Music]

Original Description

Today we learn how to query data from Pandas dataframes by using SQL statements. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎙 Discord: https://discord.gg/JU4xr8U3dm 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to use SQL statements to query and manipulate data in Pandas DataFrames, covering basic queries, filtering, and joining data frames.

Key Takeaways
  1. Install pandas and pandasql libraries
  2. Import pandas and pandasql
  3. Create a DataFrame from a CSV file
  4. Use pandasql to query the DataFrame using SQL statements
  5. Filter data based on conditions
  6. Join data frames using SQL
💡 The pandasql library allows you to use SQL statements to query and manipulate data in Pandas DataFrames, making it easier to perform data analysis tasks.

Related Reads

📰
Nigeria Machinery: A Low-Resource Industrial Dataset with a Domain-Grounded Reasoning Layer
Learn about the Nigeria Machinery dataset, a low-resource industrial dataset for African economies, and how to apply it for domain-grounded reasoning and quantitative analysis
ArXiv cs.AI
📰
The Block Universe #3: Why Spacetime Must Be Static
Learn why spacetime must be static and how it relates to personal agency in a data science context
Medium · Data Science
📰
Python 3D Cone Chart and Line Chart Combination Plot
Create interactive 3D cone and line charts in Python using popular libraries
Medium · Data Science
📰
Automating Your First Trading Signal in a Few Lines of Python [Code Included]
Automate your trading signals using Python in just a few lines of code to save time and increase efficiency
Medium · Data Science
Up next
Data Don't Lie | Powered by the UFC Insight Engine from IBM watsonx
IBM
Watch →