{"id":29640,"date":"2024-04-28T11:43:39","date_gmt":"2024-04-28T06:13:39","guid":{"rendered":"https:\/\/codeforgeek.com\/?p=29640"},"modified":"2024-04-28T11:43:40","modified_gmt":"2024-04-28T06:13:40","slug":"numpy-diff-python","status":"publish","type":"post","link":"https:\/\/codeforgeek.com\/numpy-diff-python\/","title":{"rendered":"NumPy.diff() in Python: Calculating Array Differences"},"content":{"rendered":"\n<p>Python&#8217;s NumPy library is great! Did you know it offers us a &#8216;diff&#8217; function to calculate differences? If not, this article is for you. Here, we will discuss this particular function in detail along with its parameters and its implementation. Also, we will discuss an alternative to this function. So let&#8217;s begin.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to Numpy.diff()<\/h2>\n\n\n\n<p>NumPy&#8217;s <strong>diff<\/strong> function in Python calculates differences between consecutive elements in an array. <\/p>\n\n\n\n<p>Say you have a list of numbers and you&#8217;re interested in the difference between each number and the one before it. For instance, with <strong>[5, 10, 15]<\/strong>, you&#8217;d like to know there&#8217;s a <strong>5<\/strong>-unit increase between <strong>5<\/strong> and <strong>10<\/strong>, and another <strong>5<\/strong>-unit increase between <strong>10 <\/strong>and <strong>15<\/strong>. Numpy Diff handles this task swiftly and effectively.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"477\" height=\"395\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration-5.png\" alt=\"Introduction to Numpy.diff()\" class=\"wp-image-29642\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration-5.png 477w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration-5-300x248.png 300w\" sizes=\"(max-width: 477px) 100vw, 477px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Syntax and Parameters<\/strong><\/h3>\n\n\n\n<p>Following is the Syntax of this function:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nnumpy.diff(a, n=1, axis=-1)\n<\/pre><\/div>\n\n\n<p>Now let&#8217;s learn about what each parameter means:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>a:<\/strong> This array is where you want to find the differences between consecutive elements. It can be either 1D or multi-dimensional.<\/li>\n\n\n\n<li><strong>n:<\/strong> This indicates how many times the differences are calculated recursively. By default, it&#8217;s 1, meaning it calculates differences once. You can adjust it if you need to calculate differences multiple times.<\/li>\n\n\n\n<li><strong>axis:<\/strong> This determines the axis along which differences are computed. By default, it&#8217;s -1, indicating the last axis. If your array has multiple dimensions, you can modify it to compute differences along a different axis.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Examples of NumPy.diff()<\/h2>\n\n\n\n<p>Now that we know about the function and its parameters, let&#8217;s try to implement the concept we learned and calculate differences in data. Here are some examples:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example 1<\/h3>\n\n\n\n<p>First, let&#8217;s see a simple implementation on 1-D array data.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\n\narr = np.array(&#x5B;0, 5, 10, 15, 20])\ndifferences = np.diff(arr)\nprint(&quot;Original array:&quot;, arr)\nprint(&quot;1-Dimensional Differences array:&quot;, differences)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<p>This code finds the differences between consecutive elements in the array using NumPy&#8217;s diff function. It then prints both the original array and the resulting differences.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"522\" height=\"182\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output1-3.png\" alt=\"Example 1 Output\" class=\"wp-image-29644\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output1-3.png 522w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output1-3-300x105.png 300w\" sizes=\"(max-width: 522px) 100vw, 522px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Example 2<\/h3>\n\n\n\n<p>Now let&#8217;s see if we can use the same function with multidimensional data.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\n\narr = np.array(&#x5B;&#x5B;1, 2, 3],\n                   &#x5B;4, 4, 6],\n                   &#x5B;7, 8, 10]])\ndiff_r = np.diff(arr, axis=0)\ndiff_c = np.diff(arr, axis=1)\nprint(&quot;Original 2D array:&quot;)\nprint(arr)\nprint(&quot;\\nDifferences along rows (axis=0):&quot;)\nprint(diff_r)\nprint(&quot;\\nDifferences along columns (axis=1):&quot;)\nprint(diff_c)\n<\/pre><\/div>\n\n\n<p>When <strong>axis=0<\/strong>, it means we are calculating differences <strong>along the vertical axis<\/strong>, which implies differences <strong>between consecutive rows<\/strong>. For example, the difference between the first row <strong>[1, 2, 3]<\/strong> and the second row <strong>[4, 4, 6]<\/strong> would be <strong>[4-1, 4-2, 6-3]<\/strong>, which is <strong>[3, 2, 3]<\/strong>. Likewise, the difference between the second row and the third row would be <strong>[7-4, 8-4, 10-6]<\/strong>, resulting in <strong>[3, 4, 4].<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"563\" height=\"368\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration2-5.png\" alt=\"Example 2 Illustration\" class=\"wp-image-29645\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration2-5.png 563w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration2-5-300x196.png 300w\" sizes=\"(max-width: 563px) 100vw, 563px\" \/><\/figure>\n\n\n\n<p>And when <strong>axis=1<\/strong>, differences are <strong>calculated horizontally<\/strong>, meaning <strong>between consecutive columns<\/strong>. For example, the difference between the first column <strong>[1, 4, 7]<\/strong> and the second column <strong>[2, 4, 8] <\/strong>would be <strong>[2-1, 4-4, 8-7],<\/strong> resulting in <strong>[1, 0, 1]<\/strong>. Similarly, the difference between the second column and the third column would be <strong>[3-2, 6-4, 10-8]<\/strong>, resulting in <strong>[1, 2, 2]<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"260\" height=\"379\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration3-3.png\" alt=\"Example 2 Illustration 2\" class=\"wp-image-29646\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration3-3.png 260w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration3-3-206x300.png 206w\" sizes=\"(max-width: 260px) 100vw, 260px\" \/><\/figure>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"525\" height=\"387\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output2-4.png\" alt=\"Example 2 Output\" class=\"wp-image-29647\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output2-4.png 525w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output2-4-300x221.png 300w\" sizes=\"(max-width: 525px) 100vw, 525px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Example 3<\/h3>\n\n\n\n<p>We can also calculate differences according to orders and recursion. In this example, let&#8217;s try to calculate the differences in different orders: first, second, and third. We will achieve this using the <strong>n<\/strong> parameter.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport numpy as np\n\narr = np.array(&#x5B;5, 7, 13, 18, 21])\ndiff_first_order = np.diff(arr)\ndiff_second_order = np.diff(arr, n=2)\ndiff_third_order = np.diff(arr, n=3)\n\nprint(&quot;Original array:&quot;, arr)\nprint(&quot;First-order differences array:&quot;, diff_first_order)\nprint(&quot;Second-order differences array:&quot;, diff_second_order)\nprint(&quot;Third-order differences array:&quot;, diff_third_order)\n<\/pre><\/div>\n\n\n<p>We&#8217;re finding the differences between neighbouring numbers in the array <strong>arr<\/strong> <strong>diff_first_order<\/strong> stores these differences. Then, <strong>diff_second_order<\/strong> finds differences between those differences, and <strong>diff_third_order<\/strong> calculates differences again. This helps us understand how the values change over time and their patterns.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"447\" height=\"381\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration5-3.png\" alt=\"Illustration 3 Output\" class=\"wp-image-29665\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration5-3.png 447w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/illustration5-3-300x256.png 300w\" sizes=\"(max-width: 447px) 100vw, 447px\" \/><\/figure>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img decoding=\"async\" width=\"523\" height=\"184\" src=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output3-4.png\" alt=\"Example 3 Output\" class=\"wp-image-29666\" srcset=\"https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output3-4.png 523w, https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/output3-4-300x106.png 300w\" sizes=\"(max-width: 523px) 100vw, 523px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Simple Alternatives to NumPy.diff()<\/h2>\n\n\n\n<p>Now, if you don&#8217;t wish to use the NumPy <strong>diff<\/strong> function to calculate the difference, there is an easy alternative. You can simply calculate the difference using some logic. Observe the given code closely:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\narr = &#x5B;2, 5, 7, 13, 20]\ndifferences = &#x5B;arr&#x5B;i+1] - arr&#x5B;i] for i in range(len(arr)-1)]\nprint(&quot;Original array:&quot;, arr)\nprint(&quot;Differences array:&quot;, differences)\n<\/pre><\/div>\n\n\n<p>Here we find the differences between consecutive elements in the array <strong>arr<\/strong> by subtracting each element from the next one. This generates a new array named <strong>differences<\/strong>, storing these calculated differences. Finally, we print both the original array and the differences array.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>So that&#8217;s it for this article. I hope you now have a good understanding of the topics discussed. We covered the &#8216;<strong>diff<\/strong>&#8216; function in detail, including its parameters and implementations. The examples provided were easy and simple, I hope you found them helpful. Additionally, we discussed another option to the &#8216;diff&#8217; function. Now it&#8217;s your time to try them out and use them yourself.<\/p>\n\n\n\n<p><strong><em>Further Reading:<\/em><\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/codeforgeek.com\/check-python-module-version\/\"><em>5 Best Ways to Check Python Module Versions<\/em><\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/codeforgeek.com\/python-pdfkit-module\/\"><em>Python PDFKit Module: Convert HTML, URL, and Text to PDFs<\/em><\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Reference<\/h2>\n\n\n\n<p><a href=\"https:\/\/numpy.org\/doc\/stable\/reference\/generated\/numpy.diff.html\" target=\"_blank\" rel=\"noopener\">https:\/\/numpy.org\/doc\/stable\/reference\/generated\/numpy.diff.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python&#8217;s NumPy library is great! Did you know it offers us a &#8216;diff&#8217; function to calculate differences? If not, this article is for you. Here, we will discuss this particular function in detail along with its parameters and its implementation. Also, we will discuss an alternative to this function. So let&#8217;s begin. Introduction to Numpy.diff() [&hellip;]<\/p>\n","protected":false},"author":104,"featured_media":29670,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_surecart_dashboard_logo_width":"180px","_surecart_dashboard_show_logo":true,"_surecart_dashboard_navigation_orders":true,"_surecart_dashboard_navigation_invoices":true,"_surecart_dashboard_navigation_subscriptions":true,"_surecart_dashboard_navigation_downloads":true,"_surecart_dashboard_navigation_billing":true,"_surecart_dashboard_navigation_account":true,"_uag_custom_page_level_css":"","footnotes":""},"categories":[134],"tags":[],"class_list":["post-29640","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python"],"blocksy_meta":[],"uagb_featured_image_src":{"full":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python.png",1200,600,false],"thumbnail":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python-150x150.png",150,150,true],"medium":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python-300x150.png",300,150,true],"medium_large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python-768x384.png",768,384,true],"large":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python-1024x512.png",1024,512,true],"1536x1536":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python.png",1200,600,false],"2048x2048":["https:\/\/codeforgeek.com\/wp-content\/uploads\/2024\/04\/Calculating-Differences-with-NumPy-Diff-in-Python.png",1200,600,false]},"uagb_author_info":{"display_name":"Snigdha Keshariya","author_link":"https:\/\/codeforgeek.com\/author\/snigdha\/"},"uagb_comment_info":0,"uagb_excerpt":"Python&#8217;s NumPy library is great! Did you know it offers us a &#8216;diff&#8217; function to calculate differences? If not, this article is for you. Here, we will discuss this particular function in detail along with its parameters and its implementation. Also, we will discuss an alternative to this function. So let&#8217;s begin. Introduction to Numpy.diff()&hellip;","_links":{"self":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/29640","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/users\/104"}],"replies":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/comments?post=29640"}],"version-history":[{"count":0,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/posts\/29640\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media\/29670"}],"wp:attachment":[{"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/media?parent=29640"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/categories?post=29640"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeforgeek.com\/wp-json\/wp\/v2\/tags?post=29640"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}