0
0
Pandasdata~30 mins

When to use apply vs vectorized operations in Pandas - Hands-On Comparison

Choose your learning style9 modes available
When to use apply vs vectorized operations
📖 Scenario: You work in a small online store. You have a list of product prices and want to calculate the final price after a discount. You want to learn the best way to do this using pandas.
🎯 Goal: Learn how to use vectorized operations and the apply method in pandas to calculate discounted prices. Understand when to use each method.
📋 What You'll Learn
Create a pandas DataFrame with product names and prices
Create a discount rate variable
Use vectorized operations to calculate discounted prices
Use the apply method to calculate discounted prices
Print the results to compare both methods
💡 Why This Matters
🌍 Real World
In real online stores or sales data, you often need to adjust prices or calculate new values based on existing data. Knowing when to use fast vectorized operations or flexible apply functions helps you write efficient and clear code.
💼 Career
Data analysts and data scientists frequently manipulate data tables. Understanding pandas vectorized operations and apply method is essential for cleaning, transforming, and analyzing data efficiently.
Progress0 / 4 steps
1
Create the product DataFrame
Create a pandas DataFrame called products with two columns: 'Product' and 'Price'. Add these exact rows: 'Pen', 1.20, 'Notebook', 2.50, 'Eraser', 0.50, 'Pencil', 0.80.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary where keys are column names and values are lists of column values.

2
Set the discount rate
Create a variable called discount_rate and set it to 0.1 to represent a 10% discount.
Pandas
Need a hint?

Just assign 0.1 to the variable discount_rate.

3
Calculate discounted prices using vectorized operations
Create a new column in products called 'Discounted_Vectorized'. Calculate the discounted price by subtracting discount_rate times Price from Price using vectorized operations.
Pandas
Need a hint?

Use products['Discounted_Vectorized'] = products['Price'] - products['Price'] * discount_rate.

4
Calculate discounted prices using apply and print both results
Create a new column in products called 'Discounted_Apply'. Use the apply method with a lambda function that subtracts discount_rate times the price from the price. Then print the entire products DataFrame.
Pandas
Need a hint?

Use products['Discounted_Apply'] = products['Price'].apply(lambda price: price - price * discount_rate) and then print(products).