Skip to content
Analyzing and Visualizing Data

Selecting Data


Learning Objectives

  • You can select a column and distinguish it from the complete table.
  • You can trace a comparison into a Boolean mask and the selected rows.
  • You can select complete rows using a parameter while preserving the input table.

A table can contain observations that belong to several questions. To examine Programming sessions, we need their records rather than every row. In Part 4, a loop selected matching records. Pandas can make the selection using a comparison on a column.

Selecting a Column

Replace analysis.py with this small table example. We will return to the 24-session CSV after practising selection:

import pandas as pd
sample = pd.DataFrame([
{"subject": "Programming", "minutes": 25},
{"subject": "Mathematics", "minutes": 40},
{"subject": "Programming", "minutes": 15},
{"subject": "Languages", "minutes": 20}
])
minutes = sample["minutes"]
print(minutes)

The output is:

0 25
1 40
2 15
3 20
Name: minutes, dtype: int64

sample["minutes"] selects the column named minutes. The result is a Series, a sequence of values with index labels. It contains one duration per row; it is not the table’s total. sample still refers to the complete DataFrame with both columns.

The selection uses a string key, as dictionary access did. Here, the key identifies a whole column rather than one field in one record.

A Comparison for Each Row

Add the following lines after the small table:

mask = sample["subject"] == "Programming"
print(mask)

The output is:

0 True
1 False
2 True
3 False
Name: subject, dtype: bool

The comparison produces one Boolean value for each row. This Series is called a Boolean mask. Its True values identify rows whose subject equals Programming.

Use the mask to select the rows:

selected = sample[mask]
print(selected)

The output is:

subject minutes
0 Programming 25
2 Programming 15

sample[mask] keeps the rows marked True, including all their columns. The labels 0 and 2 identify the rows retained from sample; pandas has not inserted a missing observation between them. len(selected) is 2.

The diagram below follows the selection. The comparison creates four Boolean values, and the two True values retain the corresponding records.

A column comparison produces a mask for selecting complete rows.

This operation does not remove the Mathematics or Languages records from sample. Printing sample again still shows all four observations.

A numeric comparison also produces one Boolean value per row. Add this selection after the preceding code:

mask = sample["minutes"] >= 25
selected = sample[mask]
print(selected)

The output is:

subject minutes
0 Programming 25
1 Mathematics 40

The operator >= includes the row lasting exactly 25 minutes. The familiar comparisons <, >, and == can be used in the same way. Trace a numeric selection in the next question.

Tracing a Selection

0 / 5 points

Trace this complete selection:

import pandas as pd
sessions = pd.DataFrame([
{"minutes": 18},
{"minutes": 30},
{"minutes": 42},
{"minutes": 25}
])
mask = sessions["minutes"] < 30
selected = sessions[mask]

Which description gives the mask in row order, the selected row labels, and the number of rows remaining in sessions?

Selecting from the CSV

Replace analysis.py with the following to select sessions from the full dataset:

import pandas as pd
sessions = pd.read_csv("sessions.csv")
minimum = 40
mask = sessions["minutes"] >= minimum
selected = sessions[mask]
print(len(selected))

The output is:

11

The variable minimum supplies the threshold. Eleven sessions last at least 40 minutes. The original sessions table still contains all 24 rows. If no row meets a condition, the selection is an empty DataFrame with the original columns.

Practise choosing a column, adjusting a comparison, and selecting the marked rows. Each supplied program needs one small change.

Now apply the same selection pattern in a function. Its minimum parameter supplies the threshold instead of a fixed value in the program. Return the complete matching rows, including their original columns and index labels.

Selecting Longer Study Sessions

0 / 25 points

Complete long_sessions(sessions, minimum). Return the rows whose minutes value is at least minimum.

For durations 15, 30, 45, a minimum of 30 keeps the second and third rows. Keep all columns, row labels, and row order; leave sessions unchanged. If no row qualifies, return an empty table with the original columns. Durations are numeric and have no missing values.

The selection keeps the complete records needed for a question. In the next chapter, we will calculate with their measurements and add a calculated column.

Check Your Understanding

  1. How does selecting "minutes" differ from selecting rows with a Boolean mask?
  2. If a condition matches no rows, what columns does the selected table contain? What happens to the original table?
  3. A selection function accepts a minimum parameter, but its comparison is sessions["minutes"] >= 40. Two calls use the same table and different minimum values. Why do they select the same rows, and what should control the comparison instead?