Menu
×
×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS NUMPY FOR ML Roadmap
     ❯   

ADVANCED NUMPY OPERATIONS

Broadcasting

×

Share this Topic

Share Via:

Thank you for sharing!


Broadcasting

What is Broadcasting?

Broadcasting allows NumPy to perform element-wise operations on arrays of different shapes without the need for manual reshaping or looping. Instead of repeating values, NumPy automatically expands smaller arrays to match the dimensions of larger ones.

Example: Broadcasting a 1D and 2D Array

import numpy as np
# Creating two arrays of different shapes
a = np.array([1, 2, 3])
b = np.array([[1], [2], [3]])
# Broadcasting: NumPy automatically expands 'b' to match 'a'
result = a + b
print("Array a:\n", a)
print("Array b:\n", b)
print("Broadcasted Addition Result:\n", result)

How does this work?

  • a has a shape of (3,) → [1, 2, 3]
  • b has a shape of (3,1) → [[1], [2], [3]]
  • NumPy broadcasts b to (3,3) and adds element-wise with a.

More Examples of Broadcasting

Broadcasting a Scalar to a Matrix

matrix = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10
result = matrix + scalar
print(result)
# The scalar gets "broadcasted" to each element

Real-World Use Case:

Broadcasting is widely used in machine learning for normalization, feature scaling, and batch operations.


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2025 Django-tutorial.dev .All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.