Chapter 6 exercises: Pandas: Series and DataFrames
On this page
Attempt these tasks before opening the worked answers. Use the chapter experiment notebook, or import NumPy as np and Pandas as pd in your own notebook. Retain your first attempt and explain each correction.
B2-06-E01 · Use labels and positions explicitly
Retrieve Bretoria by label and the second value by position, without s[1].
s=pd.Series([120,80,90],index=["Aland","Bretoria","Caldara"])One hint after an attempt
Compare .loc with .iloc.
B2-06-E02 · Assign without chaining
Set visits below 10 to 10 in a copy, retaining the input unchanged.
df=pd.DataFrame({"name":["N","S"],"visits":[5,12]})One hint after an attempt
Copy first and assign once.
B2-06-E03 · Align before subtracting
Calculate spare capacity by labels; explain why subtracting raw arrays in their current order is wrong.
actual=pd.Series([10,20],index=["N","S"])
expected=pd.Series([25,15],index=["S","N"])One hint after an attempt
Reindex expected to actual.index to inspect the match.
Reflect and get feedback
Explain one result without looking at the code. Identify one boundary case that would change your method. An optional tutor prompt is: “Here is my attempt at B2-06-E03. Give one hint about the violated assumption; do not give the solution yet.” Then use the worked answers.