.diff()
Published Nov 28, 2024
Contribute to Docs
In NumPy, the .diff()
function computes the difference between consecutive elements along a specified axis. It returns an array of the same shape with one less element along the specified axis, showing the differences.
Syntax
numpy.diff(a, n=1, axis=-1, prepend=<no value>, append=<no value>)
a
: The input array on which to compute the differences.n
: The number of times the difference is computed. Default is1
.axis
: The axis along which the difference is computed. Default is-1
(last axis).prepend
: Values to prepend to the array before computing the difference.append
: Values to append to the array after computing the difference.
This function returns an array of differences between consecutive elements along the specified axis, with one fewer element along that axis than the input array.
Example
In this example, the .diff()
function computes the difference between consecutive elements of the array:
import numpy as np# Array of valuesarr = np.array([1, 3, 6, 10, 15])# Compute the difference between consecutive elementsresult = np.diff(arr)print(result)
The output of the above code is shown below:
[2 3 4 5]
Codebyte Example
In this codebyte example, the .diff()
function computes the difference between consecutive elements along the columns of the 2D array:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours