Module 05 · Foundation

Select exactly what you need

Choose rows, columns, and individual cells using labels and positions.

Before you start: Know the difference between a Series and a DataFrame and recognize an index.

Python loads from this site on your first run.

Each run starts with fresh data. Download any exported files before another run. Your written answers and code drafts are saved on this device; export your work to keep a backup.

M05C01 · Explore · predict · practice

One bracket or two?

df["Score"] selects one column as a Series. df[["Score"]] passes a list of column names and returns a DataFrame, even with only one column. To select several columns, put their names in that inner list. The distinction matters when another operation expects a table.

Read the example

df = students()
column = df["Score"]
table = df[["Score"]]
result = df[["Name", "Score"]]
print(type(column).__name__, column.shape)
print(type(table).__name__, table.shape)
print(result.head(3))
Verified example output · pandas 2.2.3
Series (12,)
DataFrame (12, 1)
    Name  Score
0  Amira     88
1  Bilal     72
2  Chloe     91

Watch for this. df["Name", "Score"] is not the same as df[["Name", "Score"]] for these ordinary columns.

Your turn

Select Campus and Program, in that order, into a DataFrame named result. Print its first four rows and shape.

For the code check, keep these result variable names: result. Different valid approaches are welcome.

Show a hint

Place both exact column names inside one inner list.

Show one worked solution
df = students()
result = df[["Campus", "Program"]]
print(result.head(4))
print(result.shape)

result has 12 rows and two columns in the requested order: Campus, then Program.

Compare your explanations
  1. Read. A Python list containing the names of the columns to select.
  2. Predict. (12,) for the Series and (12, 1) for the one-column DataFrame.
  3. Explain. Brackets work consistently with names containing spaces and names that could conflict with DataFrame attributes or methods.

One quick check

Which returns a one-column DataFrame?

What you should be able to explain. I can predict whether a column selection returns a Series or a DataFrame.

M05C02 · Explore · predict · practice

Select row and column labels with loc

set_index("Student_ID") uses the student IDs as row labels and, by default, removes that field from the data columns. loc has the form table.loc[row_labels, column_labels]. A list keeps the selection table-shaped. at is convenient when you need a single value with a row label and column label.

Read the example

df = students().set_index("Student_ID")
result = df.loc[["S001", "S003"], ["Name", "Score"]]
one_score = df.at["S003", "Score"]
print(result)
print("One score:", one_score)
Verified example output · pandas 2.2.3
             Name  Score
Student_ID              
S001        Amira     88
S003        Chloe     91
One score: 91

Watch for this. set_index does not automatically check that IDs are unique; uniqueness needs its own check.

Your turn

Select S002 and S004 with Name and Campus into result. Use at to get S004's Score into one_score.

For the code check, keep these result variable names: one_score, result. Different valid approaches are welcome.

Show a hint

Provide a list of IDs on the left of the comma and a list of column names on the right.

Show one worked solution
df = students().set_index("Student_ID")
result = df.loc[["S002", "S004"], ["Name", "Campus"]]
one_score = df.at["S004", "Score"]
print(result)
print("One score:", one_score)

Bilal and Dana both belong to Dubai. Dana's individual score is 65.

Compare your explanations
  1. Read. The comma. The row labels are on the left; the column labels are on the right.
  2. Predict. Amira and Chloe appear. one_score is 91.
  3. Explain. loc looks for row labels. Without set_index, the default row labels are numbers rather than S001 and S003.

One quick check

What does loc use to select rows?

What you should be able to explain. I can read selected records and one value using meaningful labels.

M05C03 · Explore · predict · practice

Select row and column positions with iloc

iloc uses numerical positions for both rows and columns. Positions start at 0 even when the printed index labels are student IDs. A slice excludes its stop position. iat reads one value using a row position and a column position.

Read the example

df = students()[["Name", "Campus", "Score"]]
result = df.iloc[1:4, [0, 2]]
one_score = df.iat[1, 2]
print(result)
print("One score:", one_score)
Verified example output · pandas 2.2.3
    Name  Score
1  Bilal     72
2  Chloe     91
3   Dana     65
One score: 72

Watch for this. iloc expects positions, so df.iloc["S001"] is not valid positional selection.

Your turn

Select the first two rows and all three columns into result. Read the first student's score with iat into one_score.

For the code check, keep these result variable names: one_score, result. Different valid approaches are welcome.

Show a hint

Use :2 for the first two row positions and : for all column positions.

Show one worked solution
df = students()[["Name", "Campus", "Score"]]
result = df.iloc[:2, :]
one_score = df.iat[0, 2]
print(result)
print("One score:", one_score)

result contains Amira and Bilal across all three selected columns. Amira's score is 88.

Compare your explanations
  1. Read. Positions 1, 2, and 3: Bilal, Chloe, and Dana.
  2. Predict. Name and Score. The table was first arranged with columns Name, Campus, Score.
  3. Explain. The same numerical position can refer to a different column after the order changes.

One quick check

What does df.iloc[1:4] include?

What you should be able to explain. I can select a rectangular portion of a table by position.

M05C04 · Explore · predict · practice

Compare the two slice endpoints

For this sorted, unique index, a loc label slice includes both its start and stop labels. An iloc position slice excludes its stop position. Compare the selected IDs instead of assuming the two expressions return the same rows. Label slicing works best when the index is appropriately sorted and its labels are understood.

Read the example

df = students().set_index("Student_ID").sort_index()
by_label = df.loc["S002":"S004", ["Name", "Score"]]
by_position = df.iloc[1:3][["Name", "Score"]]
print("Label slice:")
print(by_label)
print("Position slice:")
print(by_position)
Verified example output · pandas 2.2.3
Label slice:
             Name  Score
Student_ID              
S002        Bilal     72
S003        Chloe     91
S004         Dana     65
Position slice:
             Name  Score
Student_ID              
S002        Bilal     72
S003        Chloe     91

Watch for this. Selecting from a selection is fine for reading; use one .loc assignment when changing the original table.

Your turn

Change by_position so that its position slice returns exactly the same three rows as by_label. Store the Boolean equality check in same, then print the selected rows and the check.

For the code check, keep these result variable names: by_position, same. Different valid approaches are welcome.

Show a hint

To include row position 3, stop at position 4.

Show one worked solution
df = students().set_index("Student_ID").sort_index()
by_label = df.loc["S002":"S004", ["Name", "Score"]]
by_position = df.iloc[1:4][["Name", "Score"]]
same = by_label.equals(by_position)
print(by_position)
print("Same result:", same)

Both results now contain S002, S003, and S004 with the same column order and labels. equals() reports True.

Compare your explanations
  1. Read. The loc label slice includes the existing stop label S004 in this sorted unique index.
  2. Predict. Three in by_label: S002, S003, S004. Two in by_position: S002 and S003.
  3. Explain. No. It means row positions 1 and 2, regardless of their index labels.

One quick check

On this sorted index, which is true?

What you should be able to explain. I can explain why a label slice and a position slice can return different rows.

Further detail: official documentation for this topic.