Aggregations Along an Axis Practice Problem
This data science coding problem helps you practice Mathematical & Statistical Operations, aggregations along an axis, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Mathematical & Statistical Operations.
- Problem ID: 54
- Problem key: 54-aggregations-along-an-axis
- URL: https://datacrack.app/solve/54-aggregations-along-an-axis
- Difficulty: easy
- Topic: Mathematical & Statistical Operations
- Module: NumPy Foundations
Problem Statement
# 🧩 Aggregations Along an Axis
---
### 🎯 Goal
Aggregating along an axis is one of the most confusing NumPy concepts — but mastering it unlocks the full power of vectorized statistics. It's the foundation of column-wise means, row-wise sums, and the batch normalization in neural networks.
---
### 🔍 What Does `axis` Mean?
For a 2D matrix with shape `(rows, cols)`:
| `axis` | Collapses... | Result shape | Example |
|:-------|:------------|:-------------|:--------|
| `axis=0` | Rows (down ↓) | `(cols,)` | Column means |
| `axis=1` | Columns (across →) | `(rows,)` | Row sums |
```
Matrix: axis=0 sum: axis=1 sum:
[[1, 2, 3],
[4, 5, 6], → [12, 15, 18] [6, 15, 24]
[7, 8, 9]]
```
Think: **axis=0 collapses rows** (you get one value per column). **axis=1 collapses columns** (you get one value per row).
---
### 💻 Task
Implement `aggregate(matrix, operation, axis)`.
---
### 📥 Input
- `matrix`: 2D list
- `operation`: string — `"sum"`, `"mean"`, `"max"`, `"min"`
- `axis`: int — `0` or `1`
### 📤 Output
- Result array (1D) as a Python list
---
### 🧩 Starter Code
```python
import numpy as np
def aggregate(matrix, operation, axis):
"""
Aggregate a 2D array along the specified axis.
Args:
matrix (list[list]): 2D input data
operation (str): "sum" | "mean" | "max" | "min"
axis (int): 0 (column-wise) or 1 (row-wise)
Returns:
list: Aggregated 1D result
"""
arr = np.array(matrix, dtype=float)
# 🧠 TODO: Dispatch to np.sum, np.mean, np.max, or np.min with the axis argument
pass
```
---
### 🔑 Key Concepts
- `np.sum(arr, axis=0)` — sum down columns (one result per column)
- `np.mean(arr, axis=1)` — mean across each row (one result per row)
- This is the NumPy equivalent of `df.mean(axis=0)` and `df.sum(axis=1)` in PandasStarter Code
import numpy as np
def aggregate(matrix, operation, axis):
"""
Aggregate a 2D array along the specified axis.
Args:
matrix (list[list]): 2D input data
operation (str): "sum" | "mean" | "max" | "min"
axis (int): 0 (column-wise) or 1 (row-wise)
Returns:
list: Aggregated 1D result
"""
arr = np.array(matrix, dtype=float)
# 🧠 TODO: Dispatch to np.sum, np.mean, np.max, or np.min with the axis argument
pass