Pandas · Calculate new columns
Google Search Analytics
Course overviewGoogle Search · Clean values and create columns

Calculate new columns

Use column-wise arithmetic to derive measurements while preserving the originals.

Step 1 of 3 · Learn

Calculate a whole column at once

Pandas arithmetic operates on every row of a Series. Use .assign(new_name=expression) to return a DataFrame with a derived column while keeping the source columns.

indexduration_ms
0125
1500
21200
indexduration_msduration_seconds
01250.125
15000.5
212001.2
Divide by 1,000 to convert milliseconds to seconds. Keep the original measurement.

Round the derived value

.round(n) rounds to n decimal places; it does not format a fixed number of displayed digits. Round after the calculation. Pandas rounds exact halfway values to the nearest even value.

indexvalue
01.234
12.346
23.111
indexvaluerounded
01.2341.23
12.3462.35
23.1113.11
The new column is rounded; the original precision is retained.
▷ Your turn

Return search_id, response_ms, and a new response_seconds column for every search. Calculate seconds as response_ms divided by 1000, without rounding. Keep source row order and save the DataFrame as result.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.