bhylu.com

Advertisements

Pandas Updating Values

Use a single loc assignment to update chosen rows in the intended DataFrame. Avoid chained selection followed by assignment to an uncertain intermediate object.

How it works

Pandas 3 uses Copy-on-Write semantics, and chained assignment cannot be relied on to modify the original table. In the browser’s Pandas 2.2 environment, explicit loc assignment is also the clearest portable contract. Make the filter and the destination columns visible together. This example changes a fictional measurement correction; a real workflow should preserve the original record and the reason for a correction.

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 updates.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.

Example

updates.py

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "drop_id": [101, 102, 103, 104],
    "point": ["north", "south", "north", "south"],
    "material": ["leaves", "food", "food", "leaves"],
    "kg": [12., 8., 6., 10.],
    "bags": pd.array([3, 2, 1, 2], dtype="Int64"),
    "day": ["2026-10-01", "2026-10-01", "2026-10-02", "2026-10-02"],
})

corrected = df.copy()
corrected.loc[corrected["drop_id"].eq(102), "kg"] = 9.
print(corrected["kg"].tolist())
print(df["kg"].tolist())

Expected result

[12.0, 9.0, 6.0, 10.0]
[12.0, 8.0, 6.0, 10.0]

The correction affects one row in the independent result, while the source remains unchanged. Tests should verify that observed behaviour rather than just search for loc or copy in source code.

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