NumPy Summations
➕ NumPy Summations
NumPy provides fast and efficient functions to calculate summations over arrays. These are vectorized operations, much faster than Python loops, and can operate along specific axes in multi-dimensional arrays.
✅ 1. Sum of All Elements (np.sum)
-
Computes the sum of all elements in the array
✅ 2. Sum Along an Axis (2D Array)
-
axis=0→ sum down the rows (column-wise) -
axis=1→ sum across columns (row-wise)
✅ 3. Cumulative Sum (np.cumsum)
-
Computes a running total of elements
✅ 4. Sum with Conditions
-
Use Boolean indexing to sum elements satisfying a condition
✅ 5. Notes & Tips
-
np.sumworks for 1D, 2D, or ND arrays -
Axis parameter is important for dimension-specific summation
-
np.cumsumis useful in time series, cumulative totals, or statistics
🎯 Practice Exercises
-
Compute the sum of all elements in a 3×3 array.
-
Compute row-wise and column-wise sums for a 2×4 array.
-
Compute the cumulative sum of
[5, 10, 15, 20]. -
Sum only the odd numbers in
[1,2,3,4,5,6,7,8,9].
