w3resource

How to reshape arrays and perform element-wise addition using NumPy?

NumPy: Broadcasting Exercise-18 with Solution

Given two 1D arrays a of shape (8,) and b of shape (4,), write a NumPy program to reshape them and perform element-wise addition using broadcasting to get a 2D array of shape (8, 4).

Sample Solution:

Python Code:

import numpy as np

# Create 1D array a of shape (8,)
a = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# Create 1D array b of shape (4,)
b = np.array([10, 20, 30, 40])

# Reshape array a to (8, 1) to enable broadcasting
a_reshaped = a[:, np.newaxis]

# Perform element-wise addition using broadcasting
result = a_reshaped + b

print(result)

Output:

[[11 21 31 41]
 [12 22 32 42]
 [13 23 33 43]
 [14 24 34 44]
 [15 25 35 45]
 [16 26 36 46]
 [17 27 37 47]
 [18 28 38 48]]

Explanation:

  • Import NumPy: Import the NumPy library to handle array operations.
  • Create 1D array a: Define a 1D array a with shape (8,).
  • Create 1D array b: Define a 1D array b with shape (4,).
  • Reshape a: Reshape array a to (8, 1) to enable broadcasting.
  • Element-wise Addition: Add the reshaped array a and array b using broadcasting to get a 2D array of shape (8, 4).
  • Print Result: Print the resulting array.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to use NumPy Broadcasting to divide 2D arrays by 1D arrays.
Next: How to use NumPy Broadcasting to add 3D and 2D arrays?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/reshape-arrays-and-perform-element-wise-addition-with-numpy.php