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.

--

--