# Python NumPy diff with examples

In this Python tutorial, we will learn how to find the difference between two NumPy arrays in Python. With Python NumPy diff, we will cover these topics.

• Python NumPy diff function
• Python numpy difference between two arrays
• Python numpy difference between two lists
• Python numpy np.diff
• Python numpy pandas diff
• Python numpy set difference
• Python numpy absolute difference
• Python numpy round difference
• Python numpy time difference
• Python numpy mean difference

## Python numpy diff

• In this section, we will discuss how to find the difference in NumPy array Python.
• To perform this particular task we are going to use the numpy.diff() function. In Python the numpy.diff() function is used to calculate the difference between values in an array along with a given axis.
• This method is available in the NumPy module package for calculating the nth discrete difference along the given axis.

Syntax:

Let’s have a look at the syntax and understand the working of numpy.diff() method

numpy.diff
(
a,
n=1,
axis=-1,
prepend=<no value>,
append=<no value>
)
• It consists of a few parameters
• a: This parameter indicates the input array whose values are nth discrete which we want to calculate.
• n: It is an optional parameter and by default, it takes 1 value. It will check the condition if no value is provided then by default it’s set as 0.
• axis: This parameter indicates the axis along the difference to be taken.

Example:

Let’s take an example and check how to get the difference in NumPy array in Python.

Source Code:

import numpy as np

new_array=np.array([16,18,20,22,24,26])
result= np.diff(new_array, n=2)
print("Difference of array by 2:",result)

In the above code, we imported the NumPy library and then defined an array by using the np.array() function. After that, we have declared n=2 as an argument in the np.diff() function where ‘n’ indicates the number of times values are differenced.

Here is the Screenshot of the following given code

## Python numpy diff function

• In this Program, we will discuss how to use the numpy diff function in Python.
• In Python the numpy.diff() function is basically calculated by out[i]=arr[i+1]-arr[i]. For example, suppose we have a one-dimensional array that contains integer values. Now we want to calculate the difference by using the diff in a loop or we will provide the axis that indicates the differences of rows and columns.

Syntax:

Here is the Syntax of the Python numpy diff function

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

Source Code:

import numpy as np

new_array = np.array([[14, 22, 25, 36],
[11, 17, 14, 29]])
new_output=np.diff(new_array, axis=0)
result = np.diff(new_array, axis=1)
print("Difference along axis=0:",new_output)
print("Difference along axis=1:",result)

The above program uses a numpy library and then instead of the ‘n’ argument, we can perform the axis operation in numpy.diff() function. Once you will print ‘new_output’ and ‘result’ then the output will display the difference of arrays.

Here is the execution of the following given code

## Python numpy difference between two arrays

• In this section, we will discuss how to find the difference between the two numpy arrays in Python.
• By using the numpy.subtract() function, we can perform this particular task. In Python the numpy.subtract() function is used to calculate the difference between two numpy arrays and it takes multiple parameters that allow you to solve the problem.
• This method is available in the NumPy module package and it always returns type either it is scaler and ndarray depending on the input array.

Syntax:

Let’s have a look at the syntax and understand the working of numpy.subtract() function

numpy.subtract
(
x1,
x2,
/,
out=None,
*,
where=True,
casting='same_kind',
order='K',
dtype=None,
subok=True,
)
• It consists of a few parameters
• x1: This parameter indicates the first numpy array for calculating the difference and it must be a broadcastable to a common shape.
• x2: This is a second numpy array.
• out: This parameter represents the location into which the output of the result is stored and by default it takes none value.
• where: If this parameter is true then it indicate to calculate the ufunc result.

Example:

Let’s take the example of numpy.subtract() function and check how it works

Source Code:

import numpy as np

new_array1 = [45, 89, 23, 34]
new_array2 = [32, 76, 14, 15]
new_result = np.subtract(new_array1, new_array2)
print("Difference of two numpy arrays:",new_result)

In the above code, we have used two numpy arrays by using the numpy.array() function. After that, we have applied the np.subtract() function and it will find the difference between array1 and array2.

Here is the implementation of the following given code

## Python numpy difference between two lists

• In this section, we will discuss how to find the difference between two lists in Python.
• By using the set() function we can solve this problem. In Python, the set() function is used to declare a set object and can convert any iterable sequence items.
• In this example first, we will create a list and assign integer values to it and then create a set of from a list and convert our lists to set by using set(list). After that, we can subtract these given sets.

Example:

Let’s take an example and check how to get the difference between two lists in Python

new_values1= [25,30,45,16,20]
new_values2 =[14,25,35,10,9]
result= set(new_values1)-set(new_values2)
print("Difference between two lists:",result)

You can refer to the below Screenshot

## Python numpy np.diff

We have already used this function in Python numpy diff topic.

## Python numpy pandas diff

• In this Program, we will discuss how to use pandas.diff() function in Python.
• In Python, this function is used to calculate the difference of a dataframe value compared with another value in the Pandas dataframe.

Syntax:

Here is the Syntax of pandas.diff() function

DataFrame.diff
(
periods=1,
axis=0
)
• It consists of a few parameters
• periods: This parameter indicates the shift for calculating difference and by default it takes ‘1’ value.
• axis: By default it takes 0 value and it signifies the rows and columns.

Source Code:

import pandas as pd
df = pd.DataFrame({'val1': [13, 16, 18, 20, 22, 24],
'val2': [13, 16, 20, 26, 78, 12],
'val3': [13, 15, 12, 18, 28, 17]})
d=df.diff(axis=1)
print(d)

In the above code, we have used the Pandas library and assigned the integer values in the dataframe. After that, we have declared a variable ‘d’ and assigned df.diff() function. Once you will print ‘d’ then the output will display the difference of values in the dataframe.

Here is the Screenshot of the following given code

## Python numpy set difference

• In this section, we will discuss how to find a set difference between two arrays in NumPy Python.
• To do this particular task we are going to use the numpy.setdiff1d(). In Python the numpy.setdiff1d() function is used to find the set difference of two numpy arrays and this function takes two arguments array1 and array2.
• This method is available in the numpy module package and always returns the unique value in numpy array1.

Syntax:

Let’s have a look at the syntax and understand the working of numpy.setdiff1d() function

numpy.setdiff1d
(
ar1,
ar2,
assume_unique=False
)
• It consists of a few parameters
• ar1: This parameter indicates the input array.
• ar2: The array which we want to compare with another one.
• assume_unique: By default it takes ‘false’ value and if it is true then the arrays are assumed to be unique.

Example:

Let’s take an example and check how to find a set difference between two numpy arrays

import numpy as np

new_array = [14, 26, 34, 42, 15]
new_array2 = [12, 16, 26]

result=np.setdiff1d(new_array, new_array2)
print("Set difference between two arrays:",result)

In the above code, we have used the numpy library and then initialize an array by using the np.array() function. After that, we have declared a variable ‘result’ and assigned the np.setdiff1d() function. Once you will print ‘result’ then the output will display the array 1 elements [14,15,34,42] which are not in array2.

Here is the execution of the following given code

## Python numpy absolute difference

• In this Program, we will discuss how to find the difference in numpy array by using numpy.absolute() function for returning the positive values.
• In Python, this is a mathematical function and measures the absolute value of each item of the array and returns positive values.
• This method is available in the NumPy module package and it takes three parameters. For example suppose we have an array that contains some numbers and now we want to subtract with another array and it will return some negative, positive values.
• If we apply the Python numpy.absolute() function then the output of the method will be a new numpy array with the positive values.

Syntax:

Here is the Syntax of the Python numpy.absolute()

numpy.absolute
(
x,
/,
out=None,
*,
where=True,
casting='same_kind',
order='K',
dtype=None,
subok=True
)

Example:

Let’s take an example and understand the working of Python numpy.absolute() function

Source Code:

import numpy as np

new_arr = ([[26,16,18],
[17 ,45,28],
[23 ,87,66]])

new_arr2 = ([[76,23,16],
[72,15,25],
[175,23,45]])
result = np.absolute(np.array(new_arr) - np.array(new_arr2))
print("Absolute value between two arrays:",result)

Here is the Output of the following given code

## Python numpy round difference

• Here we can see how to get the round difference in NumPy Python by using numpy.round() function.
• To do this task we are going to use the numpy.round() function and it is a mathematical function used for rounding the number to the nearest integer values.
• This method is available in the NumPy module package and always returns the rounded numbers. For example, suppose you have an integer number ‘2.5’ and then you have applied the numpy.round() function to get the nearest value.

Syntax:

Here is the Syntax of Python numpy.round() function

numpy.round
(
a,
decimals=0,
out=None
)

Source Code:

import numpy as np

d= np.round(2.5)
print(d)

Here is the Screenshot of the following given code

As you can see in the Screenshot the output displays the rounded value ‘2.0’

## Python numpy time difference

• In this section, we will discuss how to find the difference in time by using NumPy Python.
• To do this task we are going to use the np.datetime64() method. In Python, this method is used to get the datetime format and the date units are years(“y”), months(“m”), days(“d”).
• In this example, we can see that how to get the difference in datetime and return the time seconds.

Syntax:

Let’s have a look at the Syntax and understand the working of numpy.datetime64() method

numpy.datetime64(date)

Example:

import numpy as np

new_tim = '2022-09-10 08:25:28'
new_tim2 = '2022-09-10 04:24:20'
result = np.datetime64(new_tim) - np.datetime64(new_tim2)
print("Time difference:",result)

In the above code, we have used the numpy library and then create the variables ‘new_tim’, new_tim2′ and assigned datetime values. After that, we have used an np.datetime64() function and pass the array as an argument. Once you will print ‘result’ then the output will display the difference time between two given datetime strings.

You can refer to the below Screenshot

## Python numpy mean difference

• In this Program, we will discuss how to find the mean value difference in NumPy Python.
• By using the np.mean() function we can easily perform this task. In Python the np.mean() function is used to generate the arithmetic mean along with a given axis or multiple axes.
• In Python, this function is available in the NumPy package module and returns the arithmetic value of the array elements.

Syntax:

Here is the Syntax of numpy.mean() function

numpy.mean
(
a,
axis=None,
dtype=None,
out=None,
keepdims=<no value>,
where=<no value>
)

Source Code:

import numpy as np

new_arr1 = np.arange(2,10)
new_arr2 = np.arange(2,10)
new_output = np.mean(np.abs(new_arr1[:, None] - new_arr2))
print("Mean difference:",new_output)

In the above code, we have created an array by using the np.arange() function and then applied the np.mean() function and assigned the np.abs() along with array as an argument. Once you will print ‘new_output’ then the output will display the mean value.

Here is the implementation of the following given code

As you can see in the Screenshot the output displays the ‘2.625’ as a mean value

You may like the following Python NumPy tutorials:

In this Python tutorial, we will learn how to find the difference between two NumPy arrays in Python. Also, we will cover these topics.

• Python NumPy diff function
• Python numpy difference between two arrays
• Python numpy difference between two lists
• Python numpy np.diff
• Python numpy pandas diff
• Python numpy set difference
• Python numpy absolute difference
• Python numpy round difference
• Python numpy time difference
• Python numpy mean difference