Skip to main content
Find Difference Between Numbers In Array Using np.diff

Find Difference Between Numbers In Array Using np.diff

This tutorial help to find the differences between numbers in an array by np.diff() method. You can compare two or more array using this method.

Python np.diff()

The NumPy array method np.diff() finds the differences between numbers in an array. The np.diff() function can be used to compare two or more arrays. If only one array is provided, the difference is calculated using res[i] = arr[i+1] - arr[i].

Syntax

numpy.diff(a, n = 1, axis= -1, prepend = < no value >, append = < no value >)

Arguments

  • a: This is the source array for which the difference is found using the np.diff() function.
  • n: The number of times the array is differenced is passed as the argument to n. This is by default set to 1.
  • axis: It is used to calculate the difference. It signifies that left to right is from right to left. The value is set to -1 by default. The axis can, however, be set to 0.
  • prepend: The values appended at the beginning before performing the diff() function.
  • append: The values that are appended at the ending before performing the diff() function.

Return Value

The function np.diff() returns an array. This array contains values that represent the difference between two array integers.

Let’s takes some examples to understand np.diff() method fucntionality:

Finding the difference in a single array using np.diff()

import numpy as np

arr = np.array([12, 10, 45, 65, 3])

diff_arr = np.diff(arr)
print(diff_arr)

Output:

[ -2  35  20 -62]

** Process exited - Return Code: 0 **
Press Enter to exit terminal

We have imported numpy packages at the top of the file, created a new array and passed this array to np.diff() function.

The formula to calculate array number difference:

diff_arr[i] = arr[i+1] – arr[i]

As we can see the first index of the output array is store -2, that the difference between two array number(10-12).

The outpot have :

-2 = 10-12
35 = 45-10
20 = 65-45
-62 = 3-65

Finding the difference in a Multiple array using np.diff()

We’ll subtract the first array elements from the second array elements.

# Importing numpy as np
import numpy as np

# array
arr = np.array([[12, 10, 45, 65, 3], [45, 16, 35, 25, 83]])

# creating a new array
diff_arr = np.diff(arr, n=1, axis=0)
print(diff_arr)

Output:

[[ 33 6 -10 -40 80]]

** Process exited - Return Code: 0 **
Press Enter to exit terminal

We have imported NumPy packages at the top of the file, created two new arrays and passed this array to np.diff() function.

The formula to calculate array number difference:

diff_arr[0][i] = arr[1][i]-arr[0][i]

As we can see the first index of the output array is store -2, which is the difference between two array number (10-12).

The output has:

33 = 45-12
…
…

Leave a Reply

Your email address will not be published. Required fields are marked *