Editor

Refactor apply() to Vectorized

Advanced · Refactor · from Pandas apply(), map(), transform(): Custom Data Transformations

From the lesson: Pandas apply(), map(), transform(): Custom Data Transformations

Pandas gives you dozens of built-in methods like .sum(), .mean(), and .str.upper(). But what happens when you need to run your own custom logic on every row, column, or cell? That is where apply(), map(), and transform() come in.

Read the lesson

This code uses apply() to compute a 10% discount. Refactor it to use vectorized operations instead (no apply, no map, no loops). The output should be identical.

Print the discounted column as a list.

import pandas as pd
df = pd.DataFrame({'price': [100, 200, 50, 75]})
# Refactor this apply() to use vectorized math
df['discounted'] = df['price'].apply(lambda p: round(p * 0.9, 2))
print(df['discounted'].tolist())

More Pandas Apply and Transform exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz