Chapter 6 worked answers: Pandas: Series and DataFrames
On this page
Compare your reasoning after an attempt. Different valid implementations are welcome when they preserve the observation set and the stated meaning.
B2-06-E01 · Use labels and positions explicitly
Retrieve Bretoria by label and the second value by position, without s[1].
The two selectors happen to identify the same observation in this order but express different requests.
s=pd.Series([120,80,90],index=["Aland","Bretoria","Caldara"])
assert s.loc["Bretoria"]==s.iloc[1]==80
print(s.loc["Bretoria"],s.iloc[1])80 80
B2-06-E02 · Assign without chaining
Set visits below 10 to 10 in a copy, retaining the input unchanged.
One .loc assignment names both the row condition and the destination column.
df=pd.DataFrame({"name":["N","S"],"visits":[5,12]})
changed=df.copy();changed.loc[changed.visits<10,"visits"]=10
assert df.visits.tolist()==[5,12] and changed.visits.tolist()==[10,12]
print(changed) name visits
0 N 10
1 S 12
B2-06-E03 · Align before subtracting
Calculate spare capacity by labels; explain why subtracting raw arrays in their current order is wrong.
Expected capacity for N is 15 and for S is 25; Series arithmetic matches labels rather than current positions.
actual=pd.Series([10,20],index=["N","S"])
expected=pd.Series([25,15],index=["S","N"])
spare=expected-actual
assert spare.loc["N"]==5 and spare.loc["S"]==5
print(spare)N 5
S 5
dtype: int64
Return to practice
Change one supplied input, predict the effect and rerun your own implementation. Return to the exercise prompts to identify a task you can now explain independently.