ufunc Summations
NumPy's summation ufuncs, such as sum
and cumsum
, allow for efficient summation operations across arrays or along specified axes.
Key Topics
Basic Summation
The sum
function computes the sum of all elements in an array or along a specified axis.
Example
# Basic summation
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
sum_total = np.sum(arr)
sum_rows = np.sum(arr, axis=1)
sum_columns = np.sum(arr, axis=0)
print("Total sum:", sum_total)
print("Row-wise sum:", sum_rows)
print("Column-wise sum:", sum_columns)
Output
Total sum: 21
Row-wise sum: [6 15]
Column-wise sum: [5 7 9]
Row-wise sum: [6 15]
Column-wise sum: [5 7 9]
Explanation: The sum
ufunc aggregates array elements, either across the entire array or along specified axes (rows or columns).
Cumulative Summation
The cumsum
function computes the cumulative sum of array elements, producing an array where each element is the sum of all previous elements.
Example
# Cumulative summation
cumulative_sum = np.cumsum(arr)
print("Cumulative sum:", cumulative_sum)
Output
Cumulative sum: [1 3 6 10 15 21]
Explanation: The cumsum
ufunc calculates cumulative sums, which are useful in tracking progressive totals.
Key Takeaways
- Total Sum: Use
sum
to compute totals across arrays or axes. - Cumulative Sum: Use
cumsum
for progressive summation of array elements. - Applications: Analyze totals, track progressive values, or calculate cumulative metrics.