Concept Flow - np.sum() and axis parameter
Start with array
Choose axis parameter
Sum elements along axis
Return summed array or scalar
End
np.sum() adds numbers in an array. The axis parameter decides which direction to add: rows, columns, or all.
import numpy as np arr = np.array([[1, 2], [3, 4]]) sum_all = np.sum(arr) sum_axis0 = np.sum(arr, axis=0) sum_axis1 = np.sum(arr, axis=1)
| Step | Operation | Input Array | Axis Parameter | Result |
|---|---|---|---|---|
| 1 | Sum all elements | [[1, 2], [3, 4]] | None | 10 |
| 2 | Sum along axis=0 (columns) | [[1, 2], [3, 4]] | 0 | [4, 6] |
| 3 | Sum along axis=1 (rows) | [[1, 2], [3, 4]] | 1 | [3, 7] |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| arr | [[1, 2], [3, 4]] | [[1, 2], [3, 4]] | [[1, 2], [3, 4]] | [[1, 2], [3, 4]] |
| sum_all | undefined | 10 | 10 | 10 |
| sum_axis0 | undefined | undefined | [4, 6] | [4, 6] |
| sum_axis1 | undefined | undefined | undefined | [3, 7] |
np.sum(array, axis=None) - Sums all elements if axis=None - axis=0 sums down columns - axis=1 sums across rows - Result shape depends on axis - Useful for quick totals in arrays
axis parameter in np.sum() control?arr?arr = np.array([[1, 2, 3], [4, 5, 6]]), what is the output of np.sum(arr, axis=0)?import numpy as np arr = np.array([[1, 2], [3, 4]]) result = np.sum(arr, axis=2)
arr = np.array([[[1,2],[3,4]], [[5,6],[7,8]]]). What is the shape of the result when you run np.sum(arr, axis=1)?Pass the test and this pattern moves unknown