Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Wrangle / Preprocess lessonsTINY TABLES · REAL PYTHON · YOUR PACE
A responsible finish · W30 · 8 MIN

Vectorise before apply

Choose a simple column operation before a row function.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferChoose and combine

Understand the idea

Express a calculation directly on a Series when possible. Vectorized arithmetic applies the operation to every value.

Concept sketch: one expression, applied to every rowprice246× 1.12.24.46.6one expression, applied to every row
Illustration · not the exercise output

A small example

Prices [10, 20] × 1.1 become [11, 22]. Subtracting their original mean (15) gives [−5, 5].

Follow the code

Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.

df["adjusted"] = (df["price"] * 1.1).round(2)
df

What each part does

df["price"] * 1.1
direct vectorised arithmetic
Other choices for later exercises
map(dictionary)
a value lookup
apply(lambda x: ...)
call a function on each value

Your inputs

The editable setup on the right creates df. Run executes the setup and your work from top to bottom.

Candy shop · 6 synthetic rows
candyflavourpriceratingshelf
Gummy Bearfruity1.24.1A
Choco Popchocolate2.14.6B
Mint Bitemint1.53.8A
Berry Loopfruity2.84.4B
Cocoa Cubechocolate3.44.9A
Lemon Dropfruity1.84B

Your task · Follow

  1. A price revision raises all unit prices in df by 10%.
  2. Add adjusted as the revised price rounded to two decimals, preserving the original price.
  3. Display df.
  4. Use vectorised arithmetic; do not use apply().
Hint

Keep raw and revised prices side by side.

Reveal solution

One way to do it. Keep any supplied setup in the editor and use this in the Your work section.

df["adjusted"] = (df["price"] * 1.1).round(2)
df
Optional stretch

Compare with df["{a}"].apply(lambda x: round(x * 1.1, 2)). Which expresses the intent more directly?

Your task · Follow
  1. A price revision raises all unit prices in df by 10%.
  2. Add adjusted as the revised price rounded to two decimals, preserving the original price.
  3. Display df.
  4. Use vectorised arithmetic; do not use apply().

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display a value by leaving it on the final line.

Python starts when you open a lesson.

Output

Run your code to see what Python returns.