Compute the quantity-weighted average price per product in pandas
Quick Overview
Write a pandas function that returns the quantity-weighted average price for each product as a named, sorted float Series. It tests groupby aggregation, weighted means, handling of zero quantities and missing values, and replacing a per-group apply with vectorized sums.
Compute the quantity-weighted average price per product in pandas
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `weighted_avg_price(df)`. The input DataFrame has columns `product`, `price`, and `qty`. For each `product`, compute the quantity-weighted average price: `sum(price*qty)/sum(qty)`.
The function must:
- Return a `Series` with one weighted-average price per `product`.
- Index the result by `product`, sorted ascending.
- Name the Series `weighted_avg_price` with dtype `float64`.
Example:
```python
df = pd.DataFrame({
'product': ['A', 'A', 'B'],
'price': [10.0, 20.0, 5.0],
'qty': [1, 3, 2],
})
# A: (10*1 + 20*3) / (1+3) = 70/4 = 17.5
# B: (5*2) / 2 = 5.0
weighted_avg_price(df)
# product
# A 17.5
# B 5.0
# Name: weighted_avg_price, dtype: float64
```
```hint Two totals per product
The formula needs only two totals for each product. Think about whether you can get both from a single `groupby` without running a Python function once per group.
```
### What a Strong Answer Covers
- Computes `sum(price*qty)/sum(qty)` within each `product`, so rows with a larger `qty` move the result more than rows with a small one.
- Returns a `float64` Series named `weighted_avg_price`, indexed by `product` in ascending order.
- Says what happens when a product's quantities sum to zero, and when `price` or `qty` is missing.
- Compares a per-group `apply` with a vectorized grouped sum and gives a reason for the choice.
### Follow-up Questions
- Why pass `include_groups=False` to `apply`?
- How would you handle a group where `sum(qty)` is zero?
- How would this scale on millions of rows versus `apply`?
Overview: Write a pandas function that returns the quantity-weighted average price for each product as a named, sorted float Series. It tests groupby aggregation, weighted means, handling of zero quantities and missing values, and replacing a per-group apply with vectorized sums.
Write weighted_avg_price(df). The input DataFrame has columns product, price, and qty. For each product, compute the quantity-weighted average price: sum(price*qty)/sum(qty).
The function must:
Return a
Series
with one weighted-average price per
product
.
Index the result by
product
, sorted ascending.
Name the Series
weighted_avg_price
with dtype
float64
.