In NumPy, summation functions are included in the category of universal functions (ufuncs) and are used to compute the sum of elements in a NumPy array along specified axes. NumPy provides several summation functions to calculate different types of summations:
import numpy as np
arr = np.array([[1, 2], [3, 4]])
# Compute sum of all elements
total_sum = np.sum(arr)
# Compute sum along rows (axis=0)
row_sum = np.sum(arr, axis=0)
# Compute sum along columns (axis=1)
col_sum = np.sum(arr, axis=1)
print("Total sum:", total_sum) # Output: 10
print("Sum along rows:", row_sum) # Output: [4 6]
print("Sum along columns:", col_sum) # Output: [3 7]
import numpy as np
arr = np.array([1, 2, 3, 4])
# Compute cumulative sum
cum_sum = np.cumsum(arr)
print("Cumulative sum:", cum_sum) # Output: [ 1 3 6 10]
import numpy as np
arr = np.array([[1, 2], [3, 4]])
# Compute sum along rows (axis=0)
row_sum = np.sum(arr, axis=0)
# Compute sum along columns (axis=1)
col_sum = np.sum(arr, axis=1)
print("Sum along rows:", row_sum) # Output: [4 6]
print("Sum along columns:", col_sum) # Output: [3 7]
These summation functions are useful for various mathematical and statistical computations, such as computing total values, averages, and cumulative sums. They provide efficient and vectorized operations for working with large arrays of data in NumPy.