0
0
Pandasdata~30 mins

Vectorized operations vs loops in Pandas - Hands-On Comparison

Choose your learning style9 modes available
Vectorized operations vs loops
📖 Scenario: You work in a small store that tracks daily sales. You have a list of sales amounts for each day. You want to calculate the total sales and also add tax to each sale. You can do this by using loops or by using faster vectorized operations with pandas.
🎯 Goal: Learn how to use vectorized operations in pandas to perform calculations on data quickly, instead of using slower loops.
📋 What You'll Learn
Create a pandas DataFrame with daily sales data
Create a tax rate variable
Calculate total sales using a loop
Calculate sales with tax using vectorized operations
Print the results
💡 Why This Matters
🌍 Real World
Stores and businesses often need to calculate totals and apply taxes or discounts to many sales quickly.
💼 Career
Data scientists and analysts use vectorized operations in pandas to handle large datasets efficiently without slow loops.
Progress0 / 4 steps
1
Create the sales data
Create a pandas DataFrame called sales_data with one column named 'sales' and these exact values: 100, 150, 200, 130, 170.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary where the key is 'sales' and the value is the list of numbers.

2
Set the tax rate
Create a variable called tax_rate and set it to 0.1 (which means 10%).
Pandas
Need a hint?

Just assign 0.1 to the variable tax_rate.

3
Calculate total sales using a loop
Create a variable called total_sales and set it to 0. Then use a for loop with the variable sale to go through sales_data['sales'] and add each sale to total_sales.
Pandas
Need a hint?

Start with total_sales = 0. Then add each sale inside the loop using total_sales += sale.

4
Calculate sales with tax using vectorized operations and print results
Create a new column in sales_data called 'sales_with_tax' by multiplying sales_data['sales'] by (1 + tax_rate). Then print total_sales and print the sales_data DataFrame.
Pandas
Need a hint?

Multiply the whole sales column by 1 + tax_rate to get the new column. Use print() to show results.