Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] NumPy Diff Simply Explained [Tutorial + Video]

#1
NumPy Diff Simply Explained [Tutorial + Video]

? NumPy’s np.diff() function calculates the difference between subsequent values in a NumPy array. For example, np.diff([1, 2, 4]) returns the difference array [1 2].



Here is a simple example to calculate the Fibonacci number differences:

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() method: how to use it on a 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.

Formal Syntax


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

Calculate the n-th discrete difference along the given axis.

  • First difference: out[i] = a[i+1] - a[i] along the given axis.
  • Higher differences: use np.diff() recursively.

Argument Data Type Explanation
a array-like Array or list for which the differences should be calculated.
n int Optional, per default n=1. The order, i.e., number of repeated difference computations. If zero, returns a.
axis int Optional, per default the last axis=-1. The axis along which to calculate differences.
prepend array-like Values to prepend to array a along axis before calculating the difference.
Scalar value or array matching dimension and shape of a.
append ndarray Values to append to array a along axis before calculating the difference.
Scalar value or array matching dimension and shape of a.
Official docs

Executing the NumPy Diff Method Multiple Times


Executing the NumPy Diff Method Multiple Times
Figure: Repeatedly calling np.diff() to calculate the i-th order differences.

We can also run the NumPy diff function multiple times by setting the second optional argument n:

import numpy as np a = np.array([2, 4, 7, 4, 1, 8, 11, 12])
print(np.diff(a, n=1))
# [ 2 3 -3 -3 7 3 1] print(np.diff(a, n=2))
# [ 1 -6 0 10 -4 -2] print(np.diff(a, n=3))
# [ -7 6 10 -14 2] print(np.diff(a, n=4))
# [ 13 4 -24 16] print(np.diff(a, n=5))
# [ -9 -28 40] print(np.diff(a, n=6))
# [-19 68] print(np.diff(a, n=7))
# [87] print(np.diff(a, n=8))
# []

By defining the argument n, you 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 the same output as np.diff(np.diff(x)).

>>> np.diff([1, 2, 4], 2)
array([1])
>>> np.diff(np.diff([1, 2, 4]))
array([1])

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 of 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]] """

You can see that each row with three columns is collapsed into a row with only two columns (the differences).

Let’s make it even more complex and combine the axis with the n argument for multiple diff 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 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!

If you’re already proficient in Python, study the NumPy library in-depth and kickstart your data science career with our LeanPub bestselling book “Coffee Break NumPy”!

The post NumPy Diff Simply Explained [Tutorial + Video] first appeared on Finxter.



https://www.sickgaming.net/blog/2021/04/...ial-video/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] The Reduce Function in Python 3: Simply Explained xSicKxBot 0 24 04-21-2021, 11:44 PM
Last Post: xSicKxBot
  [Tut] [Solved] NumPy RuntimeWarning: All-NaN slice encountered xSicKxBot 0 39 04-02-2021, 11:10 AM
Last Post: xSicKxBot
  [Tut] np.ployfit() — Curve Fitting with NumPy Polyfit xSicKxBot 0 87 11-18-2020, 04:27 AM
Last Post: xSicKxBot
  [Tut] Python One Line While Loop [A Simple Tutorial] xSicKxBot 0 169 07-25-2020, 10:34 AM
Last Post: xSicKxBot
  [Tut] NumPy argpatition() xSicKxBot 0 177 07-23-2020, 08:20 AM
Last Post: xSicKxBot
  [Tut] NumPy polymulx() xSicKxBot 0 151 07-18-2020, 12:30 PM
Last Post: xSicKxBot
  [Tut] numpy.char.capitalize xSicKxBot 0 170 07-17-2020, 11:22 AM
Last Post: xSicKxBot
  [Tut] How to Convert a List to a NumPy Array? xSicKxBot 0 194 06-15-2020, 08:50 AM
Last Post: xSicKxBot
  [Tut] How to Convert List of Lists to NumPy Array? xSicKxBot 0 221 04-27-2020, 07:57 AM
Last Post: xSicKxBot
  [Tut] Python Character Set [Regex Tutorial] xSicKxBot 0 290 02-19-2020, 11:47 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
News - F4F Reveals Banjo-Kazooie Mumbo J...
Last Post: xSicKxBot
Yesterday 11:16 PM
» Replies: 0
» Views: 2
News - Review Roundup For Spiral: From T...
Last Post: xSicKxBot
Yesterday 11:16 PM
» Replies: 0
» Views: 12
Black Ops 2 Box and Name ESP | Fully Ext...
Last Post: Jaesanta
Yesterday 10:34 PM
» Replies: 55
» Views: 20949
[Tut] [FANG KILLER ICP] Will the Interne...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 8
(Indie Deal) Star Wars, No Man's Sky, Co...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9
Unity Mega Bundle 2021 On Now
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 10
Mobile - Noob Army Tycoon codes – free m...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9
AppleInsider - UK repair firm fined $147...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9
Microsoft - Securing a new world of hybr...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 8
Fedora - Using Ansible to configure Podm...
Last Post: xSicKxBot
Yesterday 05:04 PM
» Replies: 0
» Views: 9

[-]
Twitter

Copyright © SickGaming.net 2012-2020