ptp() is simply a convenient shorthand for computing an array's maximum minus its minimum in a single call, avoiding two separate reductions and a subtraction written out by hand. Like other reduction functions, it accepts an axis argument to compute the range along a specific dimension of a multi-dimensional array rather than the flattened whole.
1Understanding np.ptp()
ptp() is simply a convenient shorthand for computing an array's maximum minus its minimum in a single call, avoiding two separate reductions and a subtraction written out by hand. Like other reduction functions, it accepts an axis argument to compute the range along a specific dimension of a multi-dimensional array rather than the flattened whole.
np.ptp() is a small convenience over writing arr.max() minus arr.min() yourself — functionally identical, but slightly more direct and arguably clearer about the specific statistic being computed.
import numpy as np
arr = np.array([3, 7, 1, 9, 4])
print(np.ptp(arr))2Practical Example
Here is a real-world application of np.ptp() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 5, 3], [4, 2, 8]])
print(np.ptp(matrix, axis=0))3Best Practices
Follow these guidelines when working with np.ptp():
1. Use np.ptp() instead of manually writing arr.max() minus arr.min() for slightly clearer, more direct code
2. Use the axis argument to compute the range along a specific dimension of multi-dimensional data, such as the range of each column in a dataset
3. Be aware ptp() is sensitive to outliers, since it only depends on the two most extreme values — consider a percentile-based range if outlier resistance matters
Tip: np.ptp() is a small convenience over writing arr.max() minus arr.min() yourself — functionally identical, but slightly more direct and arguably clearer about the specific statistic being computed.
import numpy as np
arr = np.array([3, 7, 1, 9, 4])
print(np.ptp(arr))