Sales data analysis pattern in Data Analysis Python - Time & Space Complexity
When analyzing sales data, we often run patterns to summarize or find trends. Understanding how long these patterns take helps us work efficiently.
We want to know how the time to analyze grows as the sales data gets bigger.
Analyze the time complexity of the following code snippet.
import pandas as pd
def total_sales_per_product(sales_df):
result = {}
for product in sales_df['product'].unique():
total = sales_df[sales_df['product'] == product]['amount'].sum()
result[product] = total
return result
This code calculates total sales amount for each product by checking all sales entries.
- Primary operation: Looping over each unique product and filtering sales data for that product.
- How many times: Once for each unique product, and inside that, scanning the entire sales data to sum amounts.
As the number of sales entries and products grow, the time to calculate totals grows faster.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 sales entries | About 10 x number of products checks |
| 100 sales entries | About 100 x number of products checks |
| 1000 sales entries | About 1000 x number of products checks |
Pattern observation: The total work grows roughly with the number of sales times the number of unique products.
Time Complexity: O(p * n)
This means the time grows with the number of products times the number of sales entries.
[X] Wrong: "The code runs in linear time because it just loops once."
[OK] Correct: The code loops over products, and for each product, it scans all sales entries, so the work multiplies.
Understanding how nested loops affect time helps you explain your approach clearly and shows you can think about efficiency in real data tasks.
"What if we used a grouping method like pandas groupby instead? How would the time complexity change?"
Practice
groupby() in sales data analysis?Solution
Step 1: Understand the role of
Thegroupby()groupby()function groups data based on one or more columns, such as product or date.Step 2: Identify its use in sales data
Grouping allows us to summarize sales, like total sales per product or per month.Final Answer:
To summarize sales data by categories like product or date -> Option DQuick Check:
groupby()groups data for summary [OK]
- Thinking groupby deletes data
- Confusing groupby with sorting
- Assuming groupby creates charts
Solution
Step 1: Understand pandas groupby syntax
The correct syntax groups by 'product' column, then sums the 'sales' column.Step 2: Check each option
df.groupby('product')['sales'].sum() correctly usesdf.groupby('product')['sales'].sum(). Others misuse order or columns.Final Answer:
df.groupby('product')['sales'].sum() -> Option BQuick Check:
Group by product, then sum sales [OK]
- Calling sum() before groupby()
- Grouping by sales instead of product
- Selecting columns after sum()
df below, what is the output of df.groupby('product')['sales'].sum()?
product sales 0 A 100 1 B 200 2 A 150 3 B 100 4 C 300
Solution
Step 1: Group sales by product
Sum sales for each product: A = 100+150=250, B = 200+100=300, C = 300.Step 2: Write the output as pandas Series
The result shows sums indexed by product with name 'sales'.Final Answer:
product\nA 250\nB 300\nC 300\nName: sales, dtype: int64 -> Option AQuick Check:
Sum sales per product = 250, 300, 300 [OK]
- Adding sales incorrectly
- Confusing product labels
- Ignoring grouping before sum
df.groupby('month').mean('sales')Solution
Step 1: Check mean() function usage
Themean()method does not accept column names as arguments.Step 2: Correct usage for column selection
Select the 'sales' column before callingmean():df.groupby('month')['sales'].mean().Final Answer:
mean() does not take any arguments; column selection must be before mean() -> Option AQuick Check:
mean() no args; select column first [OK]
- Passing column name inside mean()
- Using groupby with wrong argument type
- Thinking sorting is required before groupby
product, month, and sales. How do you find the top-selling product for each month?Solution
Step 1: Group sales by month and product
Sum sales for each product in each month usinggroupby(['month', 'product'])['sales'].sum().Step 2: Reshape and find top product per month
Useunstack()to make products columns, thenidxmax(axis=1)to find product with max sales per month.Final Answer:
Use df.groupby(['month', 'product'])['sales'].sum().unstack().idxmax(axis=1) -> Option CQuick Check:
Group by month and product, then find max product [OK]
- Ignoring product when finding max sales
- Using max() without grouping by product
- Sorting without aggregation
Ready to prove it?
Pass the test and this pattern moves unknown
