Extract User Metrics and Daily Summaries from Order Data
SQL & DataModel answerLast updated
Perform three pandas aggregations: identify each user's highest-value order, calculate mean order value, and generate per-day order statistics.
You have a DataFrame representing e-commerce orders with the following structure:
| order_id | user_id | price | created_at |
|----------|---------|-------|------------|
| 1 | 101 | 20.5 | 2024-01-01 |
| 2 | 101 | 35.0 | 2024-01-03 |
| 3 | 102 | 15.0 | 2024-01-02 |
| 4 | 103 | 50.0 | 2024-01-04 |
| 5 | 102 | 25.0 | 2024-01-05 |
Using Python and pandas, write functions to compute the following:
Part A: For each user, identify the complete order record (order_id, user_id, price) corresponding to their most expensive purchase.
Part B: Calculate the mean price across all orders in the dataset.
Part C: Generate a summary showing, for each calendar date, the count of orders placed and the mean price on that date.
Your solution should handle typical data issues like missing values and timestamp normalization.
Hints
Hint 1
For finding rows with maximum values within groups, consider idxmax() combined with loc[] indexing
Hint 2
When aggregating by date, ensure timestamps are normalized to remove time-of-day information
Hint 3
Named aggregation in agg() lets you specify both the column and the function while controlling output column names
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests three distinct pandas patterns for data aggregation:
Part A requires locating specific rows within groups—not just computing a maximum value, but retrieving the entire row containing that maximum. The standard approach uses groupby().idxmax() to find index positions of maximum values, then loc[] to extract those rows.
Part B is straightforward scalar aggregation using mean(), which automatically excludes null values from the calculation.
Part C involves creating a derived grouping key (calendar date without time) and computing multiple statistics per group using named aggregation syntax.
Key Implementation Details
Part A: Highest-Value Order Per User
The challenge is distinguishing between "find the maximum price" and "find the order that has the maximum price."
def get_max_price_orders(df):
# Remove rows with missing prices
clean = df.dropna(subset=['price']).reset_index(drop=True)
# Find index of max-price row for each user
max_indices = clean.groupby('user_id')['price'].idxmax()
# Extract those complete rows
result = clean.loc[max_indices, ['user_id', 'order_id', 'price']]
return result.reset_index(drop=True)
Tie-breaking behavior: When multiple orders share the maximum price for a user, idxmax() returns the first occurrence in the current row order. To make this deterministic, sort by (user_id, price DESC, created_at ASC, order_id ASC) before grouping, so the earliest order wins ties.
Alternative approach using sorting:
def get_max_price_orders_sorted(df):
clean = df.dropna(subset=['price']).copy()
clean['created_at'] = pd.to_datetime(clean['created_at'])
sorted_df = clean.sort_values(
['user_id', 'price', 'created_at', 'order_id'],
ascending=[True, False, True, True]
)
return sorted_df.drop_duplicates('user_id', keep='first')[
['user_id', 'order_id', 'price']
].reset_index(drop=True)
Part B: Overall Average Price
def compute_mean_price(df):
return df['price'].mean()
This computes the per-order average, not a per-user average. The distinction matters: if one user places 100 orders and another places 1, both contribute proportionally to the mean.
Part C: Daily Statistics
def daily_summary(df):
working = df.copy()
working['created_at'] = pd.to_datetime(working['created_at'])
working['date'] = working['created_at'].dt.normalize()
return working.groupby('date').agg(
order_count=('order_id', 'count'),
mean_price=('price', 'mean')
).reset_index()
Why normalize? Real-world timestamps typically include hours, minutes, and seconds. Without normalization, orders at 9:00 AM and 3:00 PM on the same day would create separate groups. dt.normalize() truncates to midnight, or use dt.date to convert to date objects.
Expected Output
For the sample data:
Part A:
user_id order_id price
0 101 2 35.0
1 102 5 25.0
2 103 4 50.0
Part B: 29.1 (the sum 145.5 divided by 5 orders)
Part C:
date order_count mean_price
0 2024-01-01 1 20.5
1 2024-01-02 1 15.0
2 2024-01-03 1 35.0
3 2024-01-04 1 50.0
4 2024-01-05 1 25.0
Complexity
Let n = number of orders, u = number of users, d = number of distinct days.
- Part A: O(n) for groupby and idxmax, O(u) output space. Sorting variant is O(n log n).
- Part B: O(n) single pass, O(1) space.
- Part C: O(n) for datetime parsing and grouping, though groupby sorts keys by default making it O(n + d log d). Output is O(d).
Edge Cases and Considerations
-
Missing prices:
mean()andidxmax()skip NaN values. Users with all-NaN prices will causeidxmax()to fail; filter them out withdropna()first. -
Non-unique indices: If the DataFrame resulted from concatenation, index labels may repeat. Call
reset_index(drop=True)before usingloc[]withidxmax()results. -
Tie resolution: Document how ties are broken. "Earliest order wins" requires explicit sorting. "Return all tied orders" requires filtering:
df[df.price == df.groupby('user_id').price.transform('max')]. -
Count vs size: Use
counton a non-nullable column (likeorder_id) or usesize()instead.counton a nullable column will undercount if nulls exist. -
Timezone handling: Calendar dates depend on timezone. If timestamps have timezone information, convert to the target timezone before normalizing.
-
Empty DataFrame: All three operations return valid results (NaN for mean, empty frames for the others), but ensure downstream code handles these gracefully.
Complete Code
import pandas as pd
def max_price_order_per_user(df: pd.DataFrame) -> pd.DataFrame:
"""Return the order with highest price for each user."""
clean = df.dropna(subset=['price']).reset_index(drop=True)
max_idx = clean.groupby('user_id')['price'].idxmax()
return clean.loc[max_idx, ['user_id', 'order_id', 'price']].reset_index(drop=True)
def overall_average_price(df: pd.DataFrame) -> float:
"""Compute mean price across all orders."""
return float(df['price'].mean())
def daily_order_summary(df: pd.DataFrame) -> pd.DataFrame:
"""Aggregate order count and mean price by calendar day."""
working = df.copy()
working['date'] = pd.to_datetime(working['created_at']).dt.normalize()
return working.groupby('date').agg(
order_count=('order_id', 'count'),
mean_price=('price', 'mean')
).reset_index()
Common Mistakes
- Using
groupby().max()which returns the max of each column independently, creating impossible combinations - Forgetting to normalize timestamps, causing every order to be its own group
- Using
agg('count')on nullable columns without verifying nulls don't exist - Assuming
idxmax()returns all ties when it only returns the first