 Open in App
Not now

# How to calculate the difference between neighboring elements in an array using NumPy

• Last Updated : 02 Sep, 2020

Let’s see how to calculate the difference between neighboring elements in an array using NumPy library.

So, We can find out the difference between neighboring elements using numpy.diff() function of NumPy library.

Syntax: numpy.diff(arr, n, axis)

Now, let’s see an example:

Example 1:

## Python3

 `# import library``import` `numpy as np`` ` `# create a numpy 1d-array``arr ``=` `np.array([``1``, ``12``, ``3``, ``14``, ``5``,``              ``16``, ``7``, ``18``, ``9``, ``110``])`` ` `# finding the difference between``# neighboring elements``result ``=` `np.diff(arr)`` ` `print``(result)`

Output:

`[ 11  -9  11  -9  11  -9  11  -9 101]`

Example 2:

## Python3

 `# import library``import` `numpy as np`` ` `# create a numpy 2d-array``arr ``=` `np.array([[``10``, ``12``, ``14``], ``                ``[``25``, ``35``, ``45``],``                ``[``12``, ``18``, ``20``]])`` ` `# finding the difference between``# neighboring elements along row``result ``=` `np.diff(arr, axis ``=` `1``)`` ` `print``(result)`

Output:

```[[ 2  2]
[10 10]
[ 6  2]]```

Example 3:

## Python3

 `# import library``import` `numpy as np`` ` `# create a numpy 2d-array``arr ``=` `np.array([[``10``, ``12``, ``14``], ``                ``[``25``, ``35``, ``45``],``                ``[``12``, ``18``, ``20``]])`` ` `# finding the difference between``# neighboring elements along column``result ``=` `np.diff(arr, axis ``=` `0``)`` ` `print``(result)`

Output:

```[[ 15  23  31]
[-13 -17 -25]]```

My Personal Notes arrow_drop_up