{"id":89094,"date":"2024-08-20T18:00:57","date_gmt":"2024-08-20T12:30:57","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=89094"},"modified":"2024-08-20T18:16:37","modified_gmt":"2024-08-20T12:46:37","slug":"numpy-array-broadcasting","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/","title":{"rendered":"NumPy Array Broadcasting with Examples"},"content":{"rendered":"<p>NumPy broadcasting is a powerful feature that allows you to perform arithmetic operations on arrays of different shapes and sizes. It does this by automatically replicating the smaller array along the last mismatched dimension until both arrays have the same shape.<\/p>\n<p>Broadcasting is a very efficient way to perform vectorized operations, and it can be used to simplify many common numerical computing tasks. For example, you can use broadcasting to add a scalar value to all elements of an array or to multiply two arrays of different sizes element-wise.<\/p>\n<h2>Understanding Broadcasting in NumPy<\/h2>\n<p>At its core, broadcasting is NumPy&#8217;s way of making arrays with different shapes compatible with element-wise operations. Instead of manually reshaping or repeating values in arrays, NumPy automatically aligns them for you, improving both code readability and performance.<\/p>\n<p><strong>Let&#8217;s start with a basic example. Suppose we have two arrays, a and b:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import numpy as np\r\n\r\na = np.array([1.0, 2.0, 3.0])\r\nb = np.array([2.0, 2.0, 2.0])\r\nresult = a * b<\/pre>\n<p>In this case, a and b have the same shape, so the element-wise multiplication works straightforwardly. The result is [2.0, 4.0, 6.0].<\/p>\n<p><strong>Sample:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Numpy-Broadcasting-1.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-89169\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Numpy-Broadcasting-1.webp\" alt=\"Numpy Broadcasting\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h3>Broadcasting a Scalar<\/h3>\n<p>Broadcasting becomes more interesting when we introduce a scalar value. <strong>Consider this:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">a = np.array([1.0, 2.0, 3.0])\r\nb = 2.0\r\nresult = a * b<\/pre>\n<p>Now, b is a scalar, but NumPy automatically broadcasts it to match the shape of a. The result remains the same: [2.0, 4.0, 6.0].<\/p>\n<p>The magic happens behind the scenes; NumPy efficiently operates on the scalar without creating unnecessary copies of data.<\/p>\n<h3>General Broadcasting Rules<\/h3>\n<p><strong>To understand broadcasting fully, you need to grasp the general broadcasting rules:<\/strong><\/p>\n<p>NumPy compares array shapes element-wise, starting from the trailing (rightmost) dimensions.<\/p>\n<p><strong>Two dimensions are considered compatible if:<\/strong><\/p>\n<p>They are equal, or<br \/>\nOne of them is 1.<br \/>\nIf the conditions are not met, NumPy raises a ValueError, indicating incompatible shapes.<\/p>\n<p>This flexibility allows NumPy to handle arrays of different shapes intelligently. Missing dimensions are assumed to have size one.<\/p>\n<h3>Examples of Broadcasting<\/h3>\n<h4>Broadcasting with One-Dimensional and Two-Dimensional Arrays<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">a = np.array([[0.0, 0.0, 0.0],\r\n              [10.0, 10.0, 10.0],\r\n              [20.0, 20.0, 20.0],\r\n              [30.0, 30.0, 30.0]])\r\nb = np.array([1.0, 2.0, 3.0])\r\nresult = a + b<\/pre>\n<p>In this example, b is added to each row of a, resulting in broadcasting.<\/p>\n<p><strong>Sample<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Broadcasting-numpy-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-89170\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Broadcasting-numpy-.webp\" alt=\"Broadcasting numpy\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<p><strong>However, if we change b to have four elements:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">b = np.array([1.0, 2.0, 3.0, 4.0])\r\nresult = a + b  # Raises a ValueError<\/pre>\n<p>The shapes are incompatible, and broadcasting fails.<\/p>\n<p><strong>Sample:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/sample-Numpy-Broadcasting-.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-89183\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/sample-Numpy-Broadcasting-.webp\" alt=\"sample Numpy Broadcasting\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h4>Outer Operation<\/h4>\n<p>Broadcasting also simplifies outer operations. <strong>Here&#8217;s an example of outer addition between two one-dimensional arrays:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">a = np.array([0.0, 10.0, 20.0, 30.0])\r\nb = np.array([1.0, 2.0, 3.0])\r\nresult = a[:, np.newaxis] + b<\/pre>\n<p>The [:, np.newaxis] operation inserts a new axis into a, making it a two-dimensional array, which can then be broadcast with b.<\/p>\n<p><strong>Sample:<\/strong><\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Numpy-Broadcasting-sample.webp\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-89171\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/09\/Numpy-Broadcasting-sample.webp\" alt=\"Numpy Broadcasting sample\" width=\"600\" height=\"400\" \/><\/a><\/p>\n<h3>Conclusion<\/h3>\n<p>As you continue your journey with NumPy, mastering broadcasting will empower you to write more concise and readable code while optimizing computational performance. Whether you&#8217;re dealing with arrays of the same shape or combining scalars with multi-dimensional arrays, broadcasting simplifies the process, making NumPy a go-to tool for scientific computing and data manipulation tasks. With a solid understanding of broadcasting, you&#8217;re well-equipped to tackle a wide range of numerical problems and unlock the full potential of NumPy in your Python projects.<\/p>\n<p>So, embrace broadcasting, visualize your data transformations, and enjoy the productivity and efficiency it brings to your programming endeavours.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>NumPy broadcasting is a powerful feature that allows you to perform arithmetic operations on arrays of different shapes and sizes. It does this by automatically replicating the smaller array along the last mismatched dimension&#46;&#46;&#46;<\/p>\n","protected":false},"author":6,"featured_media":447410,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[385],"tags":[5611,383,5247,5665,5666,407,5286],"class_list":["post-89094","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-numpy-tutorials","tag-broadcasting-in-numpy","tag-learn-numpy","tag-numpy","tag-numpy-array-broadcasting","tag-numpy-array-broadcasting-with-examples","tag-numpy-broadcasting","tag-numpy-tutorials"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>NumPy Array Broadcasting with Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Broadcasting is NumPy&#039;s way of making arrays with different shapes that are compatible with element-wise operations.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"NumPy Array Broadcasting with Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Broadcasting is NumPy&#039;s way of making arrays with different shapes that are compatible with element-wise operations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2024-08-20T12:30:57+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-08-20T12:46:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"NumPy Array Broadcasting with Examples - TechVidvan","description":"Broadcasting is NumPy's way of making arrays with different shapes that are compatible with element-wise operations.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/","og_locale":"en_US","og_type":"article","og_title":"NumPy Array Broadcasting with Examples - TechVidvan","og_description":"Broadcasting is NumPy's way of making arrays with different shapes that are compatible with element-wise operations.","og_url":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2024-08-20T12:30:57+00:00","article_modified_time":"2024-08-20T12:46:37+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp","type":"image\/webp"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/dde481bb412350cde1ed6e389bc0deaf"},"headline":"NumPy Array Broadcasting with Examples","datePublished":"2024-08-20T12:30:57+00:00","dateModified":"2024-08-20T12:46:37+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/"},"wordCount":483,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp","keywords":["broadcasting in numpy","learn numpy","numpy","numpy array broadcasting","numpy array broadcasting with examples","numpy broadcasting","numpy tutorials"],"articleSection":["NumPy Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/","url":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/","name":"NumPy Array Broadcasting with Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp","datePublished":"2024-08-20T12:30:57+00:00","dateModified":"2024-08-20T12:46:37+00:00","description":"Broadcasting is NumPy's way of making arrays with different shapes that are compatible with element-wise operations.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/10\/numpy-broadcasting.webp","width":1200,"height":628,"caption":"numpy broadcasting"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/numpy-array-broadcasting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"NumPy Array Broadcasting with Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/dde481bb412350cde1ed6e389bc0deaf","name":"TechVidvan Team"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89094","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=89094"}],"version-history":[{"count":4,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89094\/revisions"}],"predecessor-version":[{"id":447656,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/89094\/revisions\/447656"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/447410"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=89094"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=89094"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=89094"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}