Aggregation along specific axes in NumPy - Time & Space Complexity
When we use numpy to add or average numbers along rows or columns, it takes some time depending on the data size.
We want to know how this time grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(1000, 500)
sum_rows = np.sum(arr, axis=1)
sum_cols = np.sum(arr, axis=0)
mean_rows = np.mean(arr, axis=1)
mean_cols = np.mean(arr, axis=0)
This code creates a 2D array and calculates sums and averages along rows and columns.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding or averaging all elements along one axis (rows or columns).
- How many times: For each row or column, numpy visits every element once.
When the array size grows, the number of elements to add or average grows too.
| Input Size (rows x cols) | Approx. Operations |
|---|---|
| 10 x 10 | 100 additions |
| 100 x 100 | 10,000 additions |
| 1000 x 1000 | 1,000,000 additions |
Pattern observation: The operations grow roughly with the total number of elements in the array.
Time Complexity: O(n * m)
This means the time grows proportionally to the total number of elements in the array.
[X] Wrong: "Summing along one axis only takes time proportional to the number of rows or columns, not the whole array."
[OK] Correct: Even when summing along one axis, numpy must visit every element in that axis, so it still processes all elements in the array.
Understanding how numpy processes data helps you explain performance in real tasks like data analysis or machine learning.
"What if we used numpy's sum on a 3D array along one axis? How would the time complexity change?"
Practice
axis=0 do when aggregating a 2D NumPy array?Solution
Step 1: Understand axis parameter meaning
In NumPy,axis=0means aggregation happens down the rows, combining values in each column.Step 2: Apply to 2D array
Aggregating withaxis=0summarizes each column separately.Final Answer:
Aggregates values down each column (per column) -> Option AQuick Check:
axis=0 means down rows = per column aggregation [OK]
- Confusing axis=0 with axis=1
- Thinking axis=0 aggregates rows instead of columns
- Assuming axis=0 flattens the array
arr along rows (per row)?Solution
Step 1: Identify axis for row-wise sum
Summing across columns (per row) requiresaxis=1.Step 2: Check syntax correctness
np.sum(arr, axis=1)correctly sums each row's elements.Final Answer:
np.sum(arr, axis=1) -> Option AQuick Check:
Sum per row uses axis=1 [OK]
- Using axis=0 to sum rows
- Using invalid axis like 2 for 2D array
- Forgetting to specify axis
arr = np.array([[1, 2, 3], [4, 5, 6]])
What is the output of
np.sum(arr, axis=0)?Solution
Step 1: Understand axis=0 sum
Sum down rows means add elements in each column: (1+4), (2+5), (3+6).Step 2: Calculate sums
Calculations: 1+4=5, 2+5=7, 3+6=9, so result is [5 7 9].Final Answer:
[5 7 9] -> Option BQuick Check:
Sum axis=0 adds columns down rows [OK]
- Adding rows instead of columns
- Confusing axis=0 with axis=1
- Returning flattened array instead of summed
arr = np.array([[1, 2], [3, 4]]) result = np.mean(arr, axis=2)
Solution
Step 1: Check array dimensions
The arrayarris 2D with shape (2,2), so valid axes are 0 and 1.Step 2: Validate axis parameter
Usingaxis=2is invalid and causes an error because axis 2 does not exist.Final Answer:
axis=2 is invalid for 2D array -> Option DQuick Check:
Axis must be less than array dimensions [OK]
- Using axis number too large for array
- Thinking np.mean can't be used on arrays
- Ignoring error messages
data with shape (4, 3, 2). You want to compute the sum of each 2D slice along the first axis (axis=0), resulting in a 2D array. Which code correctly does this?Solution
Step 1: Understand array shape and axis
Array shape is (4,3,2). Summing along axis=0 collapses the first dimension (4), resulting in shape (3,2).Step 2: Apply sum along axis=0
Usingnp.sum(data, axis=0)sums all 4 slices element-wise, producing a 2D array.Final Answer:
np.sum(data, axis=0) -> Option CQuick Check:
Sum axis=0 collapses first dimension to 2D [OK]
- Using wrong axis and getting wrong shape
- Summing all elements without axis
- Confusing axis numbering in 3D arrays
Ready to prove it?
Pass the test and this pattern moves unknown
