NumPy – Using ndarray.ptp() method (5 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

Introduction

In this tutorial, we will delve into the NumPy library, focusing on the ndarray.ptp() method, an invaluable tool for statistical analysis and data processing. The ptp() function, short for ‘peak to peak’, calculates the range of values (maximum-minimum) along a specified axis of an ndarray, which is crucial in many applications such as data normalization, feature scaling, and understanding data dispersion.

Introduction to ptp() Method

Before we dive into examples, it’s important to understand what the ptp() method does. Syntax of ndarray.ptp() is simple as follows:

ndarray.ptp(axis=None, out=None, keepdims=False)

Here, axis specifies the axis along which to calculate the range. If axis=None, the method computes the range of the flattened array. The out parameter allows specification of a different output array to place the result. The keepdims argument, when set to True, retains the reduced dimensions as 1 in the output shape.

Example 1: Basic Usage of ptp()

Let’s start with the basics. To use ptp(), you first need to import NumPy:

import numpy as np

# Create a simple array
arr = np.array([4, 2, 7, 1])

# Apply ptp()
result = arr.ptp()

print("Range: ", result)

Output:

Range:  6

This example demonstrates the range (7 – 1) of the array elements, which is 6.

Example 2: Applying ptp() Along an Axis

import numpy as np

# Create a 2D array
arr = np.array([[4, 2, 7], [1, 5, 9]])

# Apply ptp() along the first axis (column-wise)
result = arr.ptp(axis=0)

print("Column-wise range: ", result)

# Apply ptp() along the second axis (row-wise)
result = arr.ptp(axis=1)

print("Row-wise range: ", result)

Output:

Column-wise range:  [3 3 2]
Row-wise range:  [5 8]

This showcases applying the ptp() method along different axes of a 2D array, calculating a range for each column and row, respectively.

Example 3: 3D Array and Keepdims

Expanding our exploration, let’s apply ptp() to a 3D array with the keepdims parameter:

import numpy as np

# Create a 3D array
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

# Apply ptp() with keepdims=True
result = arr.ptp(axis=1, keepdims=True)

print("With keepdims=True:\n", result)

Output:

With keepdims=True:
  [[[3 3 3]]

[[3 3 3]]]

This example illustrates how ptp() can be utilized in multidimensional arrays and highlights the use of the keepdims argument to preserve the dimensions of the output.

Example 4: Excluding NaN values with nanptp()

Working with real-world data often means dealing with missing values. Here’s how you can calculate the range while skipping over NaN (Not a Number) values:

import numpy as np

# Note: nanptp() is illustrative and doesn't actually exist in NumPy as of the last update. Make sure to handle NaNs manually when using ptp().

# Handling NaN values before applying ptp()
arr = np.array([2, np.nan, 4, 6])
arr_clean = arr[~np.isnan(arr)]
result = arr_clean.ptp()

print("Range excluding NaN: ", result)

Output:

Range excluding NaN:  4.0

Though nanptp() as shown is fictional, it stresses the importance of pre-processing to handle NaN values before performing operations like ptp().

Example 5: Advanced Usage – Calculating Range of Image Pixel Values

This example ventures into a practical application, showcasing how ptp() can be used to calculate the range of pixel values in image processing:

import numpy as np
from PIL import Image

# Convert an image to a NumPy array
img = Image.open('example.jpg').convert('L')  # Convert to grayscale
img_arr = np.array(img)

# Calculate the range of pixel values
pixel_range = img_arr.ptp()

print("Pixel range: ", pixel_range)

This application displays the scope of the ptp() method beyond basic numerical datasets, emphasizing its utility in fields such as image processing.

Conclusion

To conclude, the ptp() method in NumPy offers a straightforward and efficient way to compute the range of data. Its utility spans from simple array operations to advanced applications like image processing, making it a versatile tool in the repertoire of Python data scientists and engineers.