How to find range of a NumPy array elements?

Given a NumPy array, we have to find range of its elements.
Submitted by Pranit Sharma, on March 07, 2023

Problem statement

Suppose that we are given a numpy array of shape 2x4 and we need to calculate the range of the array along the row and the column.

The range of the array along the row can be defined as the max value – min value in that row and similarly for a column.

Finding range of a NumPy array elements

To find range of a NumPy array elements, we have numpy.ptp() method which stands for peak to peak and it returns the range of values (maximum-minimum) along an axis.

The ptp() preserves the data type of the array. This means the return value for an input of signed integers with n bits (e.g. np.int8, np.int16, etc) is also a signed integer with n bits.

To find the range along the row, we need to set axis = 1 and axis = 0 for the column.

Let us understand with the help of an example,

Python program to find range of a NumPy array elements

# Import numpy
import numpy as np

# Creating array
arr = np.array([[4, 9, 2, 10],[6, 9, 7, 12]])

# Display Original array
print("Original array:\n",arr,"\n")

# Finding range along the row
row = np.ptp(arr,axis=1)

# Display result
print("range along the row:\n",row,"\n")

# Finding range along the column
col = np.ptp(arr,axis=0)

# Display result
print("range along the column:\n",col,"\n")

Output

The output of the above program will be:

Example: How to find range of a NumPy array elements?

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.