Module 3 · pandas · Lesson 17 of 66

Filtering rows and working with the index

Keep rows that pass a test, and reset, set or stack the index.

In this lesson · about 16 minutes

  • Filter rows with conditions, combined with & and |
  • Reset and set the index
  • Read a multi-level index with loc and xs

Just like NumPy, a comparison gives a table of True and False. Put a condition on one column inside the brackets to keep the rows where it's True: df[df['W'] > 0]. Then you can pick columns from the result.

For two conditions, wrap each in parentheses and join them with & (and) or | (or). Python's words and/or don't work here.

Exercise

Rows where X is negative

Select the rows where X is less than 0, and show only column Z for them.

Code that runs before yours
import numpy as np
import pandas as pd
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())

Exercise

Either condition

Select the rows where W is above 0 or Z is above 0.

Code that runs before yours
import numpy as np
import pandas as pd
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())

Reset and set the index

df.reset_index() moves the index into a normal column and numbers the rows 0, 1, 2…. df.set_index('States') does the opposite: it makes a column the new index.

Multi-level index

An index can have levels, like groups with numbered rows inside each. Use df.loc['G1'] for one outer group, then .loc[1] inside it. df.xs(1, level='Num') takes a cross-section: row 1 from every group at once.

Exercise

Group 2, row 2

Using df with the Group/Num index above, get the value in column B for group G2, row 2.

Code that runs before yours
import numpy as np
import pandas as pd
np.random.seed(101)
outside = ['G1', 'G1', 'G1', 'G2', 'G2', 'G2']
inside = [1, 2, 3, 1, 2, 3]
hier_index = pd.MultiIndex.from_tuples(list(zip(outside, inside)), names=['Group', 'Num'])
df = pd.DataFrame(np.random.randn(6, 2), index=hier_index, columns=['A', 'B'])

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.