NumPy ediff1d()

The numpy.ediff1d() function calculates the differences between consecutive elements of an array. If the input array is multidimensional, it is flattened before computing the differences.

Syntax

</>
Copy
numpy.ediff1d(ary, to_end=None, to_begin=None)

Parameters

ParameterTypeDescription
aryarray_likeInput array whose consecutive differences are computed. It is flattened if it is multidimensional.
to_endarray_like, optionalValue(s) to append at the end of the difference result.
to_beginarray_like, optionalValue(s) to prepend at the beginning of the difference result.

Return Value

Returns a NumPy array containing the differences between consecutive elements of ary. If to_end or to_begin parameters are specified, the additional values are included in the output.


Examples

1. Basic Usage of numpy.ediff1d()

Computing differences between consecutive elements in a one-dimensional array.

</>
Copy
import numpy as np

# Define an input array
arr = np.array([1, 2, 4, 7, 11])

# Compute the consecutive differences
differences = np.ediff1d(arr)

# Print the result
print("Differences:", differences)

Output:

Differences: [1 2 3 4]

The differences are computed as [2-1, 4-2, 7-4, 11-7] → [1, 2, 3, 4].

2. Applying numpy.ediff1d() on a Multidimensional Array

When applied to a multidimensional array, it is first flattened before computing the differences.

</>
Copy
import numpy as np

# Define a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])

# Compute consecutive differences
differences = np.ediff1d(arr)

# Print the result
print("Differences:", differences)

Output:

Differences: [1 1 1 1 1]

The 2D array is flattened to [1, 2, 3, 4, 5, 6], then differences are computed as [2-1, 3-2, 4-3, 5-4, 6-5].

3. Using the to_begin and to_end Parameters

Prepending and appending values to the result.

</>
Copy
import numpy as np

# Define an input array
arr = np.array([3, 8, 15, 24])

# Compute differences with additional values at the start and end
differences = np.ediff1d(arr, to_begin=0, to_end=99)

# Print the result
print("Differences with to_begin and to_end:", differences)

Output:

Differences with to_begin and to_end: [  0   5   7   9  99]

The differences are [5, 7, 9], with 0 prepended and 99 appended to the result.

4. Using numpy.ediff1d() on a Large Sequence

Computing differences in a large sequence of numbers.

</>
Copy
import numpy as np

# Generate a sequence of numbers from 1 to 10
arr = np.arange(1, 11)

# Compute consecutive differences
differences = np.ediff1d(arr)

# Print the result
print("Differences:", differences)

Output:

Differences: [1 1 1 1 1 1 1 1 1]

The differences are [1, 1, 1, 1, 1, 1, 1, 1, 1] since the sequence increases by 1 at each step.