0
0
Pandasdata~20 mins

apply() with lambda functions in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using apply() with lambda functions in pandas
📖 Scenario: You work in a small bookstore. You have a list of books with their prices and quantities sold. You want to calculate the total sales for each book.
🎯 Goal: Build a pandas DataFrame with book data, then use apply() with a lambda function to calculate total sales for each book.
📋 What You'll Learn
Create a pandas DataFrame called books with columns 'Title', 'Price', and 'Quantity' using the exact data provided.
Create a variable called calculate_sales that holds a lambda function to multiply Price and Quantity.
Use apply() with the calculate_sales lambda function on the DataFrame rows to create a new column 'TotalSales'.
Print the books DataFrame to show the new 'TotalSales' column.
💡 Why This Matters
🌍 Real World
Calculating total sales for products is a common task in retail and business analytics to understand revenue.
💼 Career
Data analysts and data scientists often use pandas apply() with lambda functions to quickly transform and analyze tabular data.
Progress0 / 4 steps
1
Create the books DataFrame
Import pandas as pd and create a DataFrame called books with these exact columns and data: 'Title' with values 'Book A', 'Book B', 'Book C'; 'Price' with values 10.0, 15.5, 8.75; and 'Quantity' with values 5, 3, 10.
Pandas
Need a hint?

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

2
Create a lambda function to calculate sales
Create a variable called calculate_sales and assign it a lambda function that takes a row and returns the product of the 'Price' and 'Quantity' columns from that row.
Pandas
Need a hint?

The lambda function should take one argument (a row) and return row['Price'] * row['Quantity'].

3
Use apply() with the lambda function
Use the apply() method on the books DataFrame with the calculate_sales lambda function and axis=1 to apply it row-wise. Assign the result to a new column called 'TotalSales' in the books DataFrame.
Pandas
Need a hint?

Remember to use axis=1 to apply the function to each row.

4
Print the DataFrame with total sales
Write a print() statement to display the books DataFrame with the new 'TotalSales' column.
Pandas
Need a hint?

Use print(books) to show the DataFrame.