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)

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
total = np.sum(arr)

print(total) # 15

  • Computes the sum of all elements in the array


✅ 2. Sum Along an Axis (2D Array)

arr2d = np.array([[1, 2, 3],
[4, 5, 6]])
# Sum of each column (axis=0)
col_sum = np.sum(arr2d, axis=0)
print(“Column sum:”, col_sum) # [5 7 9]

# Sum of each row (axis=1)
row_sum = np.sum(arr2d, axis=1)
print(“Row sum:”, row_sum) # [6 15]

  • axis=0 → sum down the rows (column-wise)

  • axis=1 → sum across columns (row-wise)


✅ 3. Cumulative Sum (np.cumsum)

arr = np.array([1, 2, 3, 4])
cum_sum = np.cumsum(arr)
print(cum_sum) # [ 1 3 6 10]

  • Computes a running total of elements

arr2d = np.array([[1,2,3],[4,5,6]])
cum_sum_axis0 = np.cumsum(arr2d, axis=0)
cum_sum_axis1 = np.cumsum(arr2d, axis=1)
print(“Cumsum axis=0:\n”, cum_sum_axis0)
# [[1 2 3]
# [5 7 9]]

print(“Cumsum axis=1:\n”, cum_sum_axis1)
# [[ 1 3 6]
# [ 4 9 15]]


✅ 4. Sum with Conditions

arr = np.array([1, 2, 3, 4, 5, 6])
# Sum only even numbers
even_sum = np.sum(arr[arr % 2 == 0])
print(even_sum) # 12 (2+4+6)
  • Use Boolean indexing to sum elements satisfying a condition


✅ 5. Notes & Tips

  • np.sum works for 1D, 2D, or ND arrays

  • Axis parameter is important for dimension-specific summation

  • np.cumsum is useful in time series, cumulative totals, or statistics


🎯 Practice Exercises

  1. Compute the sum of all elements in a 3×3 array.

  2. Compute row-wise and column-wise sums for a 2×4 array.

  3. Compute the cumulative sum of [5, 10, 15, 20].

  4. Sum only the odd numbers in [1,2,3,4,5,6,7,8,9].

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *