Understand Reduction Functions

Reduction functions in NumPy aggregate the elements of an array into a single value. These functions are useful for tasks such as calculating statistics, finding minimum or maximum values, and computing sums or products.

Common Reduction Functions

Sum: Calculates the sum of all elements in an array.

Python

import numpy as np

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

Product: Calculates the product of all elements in an array.

Python

result = np.prod(arr)

Minimum: Finds the minimum value in an array.

Python

result = np.min(arr)

Maximum: Finds the maximum value in an array.

Python

result = np.max(arr)

Mean: Calculates the average value of the elements in an array.

Python

result = np.mean(arr)

Median: Finds the median value of the elements in an array.

Python

result = np.median(arr)

Standard Deviation: Calculates the standard deviation of the elements in an array.

Python

result = np.std(arr)

Variance: Calculates the variance of the elements in an array.

Python

result = np.var(arr)

Axis-Wise Reductions

For multidimensional arrays, reduction functions can be applied along specific axes. This allows you to calculate statistics for rows, columns, or other dimensions.

Python

arr2d = np.array([[1, 2, 3], [4, 5, 6]])

# Sum along the rows
row_sum = np.sum(arr2d, axis=0)

# Sum along the columns
col_sum = np.sum(arr2d, axis=1)

Custom Reduction Functions

You can also create custom reduction functions using NumPy’s ufunc objects. These functions can be applied element-wise to arrays and combined with other reduction functions.

Python

def my_func(x):
    return x**2

result = np.sum(my_func(arr))

By effectively using reduction functions, you can efficiently analyze and summarize data in NumPy, gaining valuable insights into your datasets.

Elementwise Operations and Broadcasting
Shape Manipulation and Sorting

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?