**The NumPy diff function “np.diff()” calculates the difference between subsequent values in a NumPy array.**

Here is an example:

import numpy as np # Fibonacci Sequence with first 8 numbers fibs = np.array([0, 1, 1, 2, 3, 5, 8, 13, 21]) diff_fibs = np.diff(fibs) print(diff_fibs) # [1 0 1 1 2 3 5 8]

This code snippet shows the most simple form of the np.diff() function: using it on a simple one-dimensional NumPy array. It calculates the difference between two subsequent values of a NumPy array. Hence, an array with n elements results in a diff array with (n-1) elements.

We can also run the NumPy diff function multiple times by defining the argument “n”:

import numpy as np # Fibonacci Sequence with first 8 numbers fibs = np.array([0, 1, 1, 2, 3, 5, 8, 13, 21]) print(np.diff(fibs, n=1)) # [1 0 1 1 2 3 5 8] print(np.diff(fibs, n=2)) # [-1 1 0 1 1 2 3]

By defining the argument n, we can execute the diff function multiple times on the respective output of the last execution. Hence, the call np.diff(x, n=2) results in exactly the same output as np.diff(np.diff(x)).

## NumPy Diff with Two Axes

But what happens if you have a two-dimensional NumPy array? In other words, how does the diff function work with multiple axes?

Here is an example how you can use the diff function to calculate the differences along the columns (axis=1):

import numpy as np a = np.array([[0, 1, 1], [2, 3, 5], [8, 13, 21]]) diffs = np.diff(a, axis=1) print(diffs) """ [[1 0] [1 2] [5 8]] """

Let’s make it even more complex and combine the axis argument with the “n” argument for multiple diffs executions in a single function call:

import numpy as np a = np.array([[0, 1, 1], [2, 3, 5], [8, 13, 21]]) diffs = np.diff(a, n=2, axis=1) print(diffs) """ [[-1] [ 1] [ 3]] """

In this puzzle, we use the axis argument axis=1 which means that we calculate the differences along the columns. For example, the first column results in the diff array [0 1].

When defining the parameter n, the diff function is applied n times to the output of the previous diff function execution. Thus, the first column undergoes the following transformations:

[0 1 1]diff--> [1 0]diff--> [-1]

## Where to go from here?

Having a proficient Python education is critical for your success as a developer. You cannot hope to master data science if you do not even know the most basic Python and computer science concepts. To this end, I have created a free Python email course (+ Bonus Cheat Sheet series).

Subscribe if you need to refresh your basic Python knowledge! It’s fun!

**“I have never learned so deeply! You are awesome” — Myu, Subscriber**

## Comments

short and simple

Thanks!