0
0
Pandasdata~15 mins

apply() on rows (axis=1) in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using apply() on rows with axis=1 in pandas
📖 Scenario: You work in a small bookstore. You have a table of books with their prices and quantities. You want to find the total value of each book's stock.
🎯 Goal: Create a pandas DataFrame with book data, then use apply() on rows (axis=1) to calculate the total value 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 function called calculate_value that takes a row and returns the product of Price and Quantity.
Use apply() on books with axis=1 and the calculate_value function to create a new column TotalValue.
Print the books DataFrame to show the new column.
💡 Why This Matters
🌍 Real World
Calculating total stock value helps bookstores and shops understand their inventory worth quickly.
💼 Career
Data analysts and data scientists often use apply() on rows to create new features or calculate values based on multiple columns.
Progress0 / 4 steps
1
Create the books DataFrame
Create a pandas DataFrame called books with these exact columns and data: Title with values 'Book A', 'Book B', 'Book C'; Price with values 10, 15, 7; 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 the calculate_value function
Create a function called calculate_value that takes one argument row and returns the product of row['Price'] and row['Quantity'].
Pandas
Need a hint?

Define a function with def that multiplies row['Price'] and row['Quantity'].

3
Apply the function to each row
Use apply() on the books DataFrame with axis=1 and the calculate_value function to create a new column called TotalValue.
Pandas
Need a hint?

Use books['TotalValue'] = books.apply(calculate_value, axis=1) to add the new column.

4
Print the books DataFrame
Print the books DataFrame to show the new TotalValue column.
Pandas
Need a hint?

Use print(books) to display the DataFrame with the new column.