How to obtain the range of values along an array's axis

Overview

The ptp() function in NumPy obtains the range of values along a given array's axis.

Range = maximum value - minimum value

Axes in NumPy are defined for any given array having more than one dimension (e.g., a 2-D array). A 2-D array has two corresponding axes, axis 0 and axis 1. Axis 0 runs vertically downwards across rows while axis 1 runs horizontally across columns.

Syntax

The syntax for the ptp() function is given below:

numpy.ptp(a, axis=None, out=None, keepdims=<no value>)
The syntax of the ptp() method

Parameter values

The ptp() function takes the following parameter values:

  • a: This is the input array and is a required value.
  • axis (optional): This is the axis along which the range is to be determined. The value may also take a negative. In that case, it counts from the last to the first axis. This is an optional parameter.
  • out(optional): This is an array-like object in which the result obtained is to be stored. This is an optional parameter.
  • keepdims (optional): This takes a Boolean value indicating whether or not the axes reduced are left in the results as dimensions with size one. This is an optional parameter.

Return value

The ptp() function returns an array holding the result.

Example

Let's view the code for this method.

import numpy as np
# creating an input array
my_array = np.array([[1, 2, 5, 9], [3, 10, 4, 7]])
# obtaining the range from axis 0
print(np.ptp(my_array, axis=0))
# obtaining the range from axis 1
print(np.ptp(my_array, axis=1))

Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array, my_array using the array() function.
  • Line 6: We use the ptp() function to obtain and then print the range of values from axis 0.
  • Line 9: We use the ptp() function to obtain and then print the range of values from axis 1.

    Free Resources