Data Analysis with Python: From Raw Data to Real-World Insights
BOOK 2 · PANDAS · CHAPTER 9

Chapter 9 exercises: Combining and Reshaping Data

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-09-E01 · Reject a multiplying lookup

Show that the declared many-to-one merge fails instead of returning four apparent observations.

left=pd.DataFrame({"id":[1,2],"key":["N","N"]})
right=pd.DataFrame({"key":["N","N"],"region":["a","b"]})
One hint after an attempt

Validate the right-hand key uniqueness.

B2-09-E02 · Retain unmatched observations

Use a left merge and report the unmatched key without discarding it.

left=pd.DataFrame({"key":["N","S"]})
right=pd.DataFrame({"key":["N"],"region":["North"]})
One hint after an attempt

Inspect the merge indicator.

B2-09-E03 · Reshape a unique key

Create four institution-year observations and verify the combined key.

wide=pd.DataFrame({"institution":["N","S"],"2022":[10,8],"2023":[15,11]})
One hint after an attempt

Identify the columns that stay as identifiers.

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-09-E03. Give one hint about the violated assumption; do not give the solution yet.” Then use the worked answers.

Teaching edition · verified experiments · PDF and EPUB editions not generated.