Q#18: Filtering student information with Pandas

Suppose you have a dataframe, df, with the following records:

The dataframe is showing information about students. Write code using Python Pandas to select the rows where the students’ favorite color is green or yellow and their grade is between 85–95 (inclusive).

TRY IT YOURSELF

Link to free notebook here: https://colab.research.google.com/drive/1G9ACidj_ZVi4UeWLY-K539XzErsOe7sJ?usp=sharing

ANSWER

This question tests your knowledge of Python, specifically the popular package Pandas.

There are many ways to filter rows in Pandas, here we use a relatively recent method utilizing the query method. This allows us to write our logical statements very much like SQL queries (the quotes are important):

df.query('(Favorite_Color == “yellow” or Favorite_Color == “green”) and (Grade >= 85 and Grade <= 95)')

Another, more common way is to write the filters as slicers within the dataframe:

df[(df['Favorite_Color'] == 'yellow' or df['Favorite_Color'] == 'green') and (df['Grade'] >= 85 and df['Grade']<=95)]

Note, the easier readability with the query method.

--

--

--

Data Science tutorial working through solutions to Data Science Interview Questions

Recommended from Medium

Python to C++, A Data Scientist’s Journey to Learning a New Language — Functions

Master Data Management (MDM): Top 10 Definitions

Breathing and Covid: Asian “x95” Masks for Seniors

Working with structured data in Python using Pandas

Linear Regression Model on the New York Taxi Trip Duration Dataset using Python

Exploratory Data Analysis for Machine Learning (summary of notes)

Basic of Statistics: Mean, Median and Mode

Are you using data visualization in your communications?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abish Pius

Abish Pius

Data Science Professional who teaches with unflashy, simple to understand python code.

More from Medium

Let’s Understand the Important Pandas Functions for Data Science

Real Life Examples of Pandas — Ẹ Gbà Ẹ Tọwó

What is Pandas? — Master Data Analysis with Python Chapter 1

Is Pandas the Only Library to Open Datasets?