Pandas · Update values safely
Google Search Analytics
Course overviewGoogle Search · Clean values and create columns

Update values safely

Set values with loc and choose between where and mask without chained assignment.

Step 1 of 3 · Learn

Update in one assignment

Create a copy when you want a separate working table. Use a single .loc[condition, column] = value assignment to update matching rows; avoid chained assignments such as df["flag"][condition] = value.

indexscore
010
120
230
indexscoreflag
010keep
120keep
230review
Set a default, then change only matching rows in the working copy.

Keep or replace matching values

where(condition, other) keeps values where the condition is True and replaces the rest. mask(condition, other) does the reverse: it replaces values where the condition is True.

indexscore
010
120
230
indexscorecapped
01010
12020
23020
Keep values at or below 20; replace larger values in the derived column.

Preserve the original measurement

Apply display caps and labels to a derived column, not the raw measurement. Assign the result of where() or mask() back to a column; calling either method alone does not update the DataFrame.

▷ Your turn

Return search_id, response_ms, and response_flag for every search. Set response_flag to "slow" when response_ms is greater than 300; otherwise set it to "within_target". Keep response_ms unchanged and preserve source row order. Save the DataFrame as result.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.