w3resource

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


18. Reshape 1D Arrays for 2D Addition

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.

For more Practice: Solve these Related Problems:

  • Reshape two 1D arrays into a (8,1) and (1,4) array respectively, then add them to produce an (8,4) array.
  • Create a function that takes two 1D arrays of different lengths and uses np.reshape to make them broadcast-compatible for addition.
  • Implement a solution that checks the dimensions of two arrays and automatically reshapes them to allow element-wise addition.
  • Test the addition on arrays with both integer and float values to ensure the resulting array has the expected type.

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.



Follow us on Facebook and Twitter for latest update.