bhylu.com

Advertisements

Pandas Index Alignment Exercise

A correction table arrives in a different order from the report. Apply the corrections by identity and explain why copying its raw array would produce the wrong result.

Your brief

Labels are part of the calculation. Construct two Series over the same identities but in different orders, then assign the correction Series to the labelled table. Pandas aligns it by index. Before using this technique with real data, require unique correction keys and check that the required report keys are covered. Missing matches otherwise create unknown values, and extra correction keys can go unused without an exception.

Run the code

Select Try in playground to load the complete editable source. Nothing executes until you choose Run. The browser uses Pyodide 0.27.7, Pandas 2.2.3 and NumPy 2.0.2. Each ordinary execution starts a fresh isolated runtime. The tables are fictional and do not use personal files.

For local work, use a separate virtual environment and run python exercises.py. Download the complete source. The reviewed local environment uses Python 3.12.14, Pandas 3.0.6 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with Pandas 2.2.3 and NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Worked solution

Show the worked solution
exercises.py

import pandas as pd
import numpy as np

report = pd.DataFrame({"kg":[12.,8.]}, index=[101,102])
corrections = pd.Series([9.,13.], index=[102,101])
assert corrections.index.is_unique
assert report.index.isin(corrections.index).all()
report["kg"] = corrections
print(report["kg"].tolist())
print(float(report.loc[101,"kg"]))

Expected result

[13.0, 9.0]
13.0

Identity 101 receives thirteen kilograms although its correction appears second. The coverage assertion makes a missing correction fail rather than quietly becoming a missing value. This is a label-based update, not a positional replacement.

Extend and test

Remove correction 102 and confirm the assertion fails. Then write a separate policy that deliberately preserves uncorrected original values.

Use Pandas’s official reference for precise contracts, supported versions and numerical limitations.

Advertisements