w3resource

Add 1D array to each Row of 2D array using np.add in NumPy


Broadcasting Behavior:

Write a NumPy program that creates a 2D NumPy array and a 1D array. Use the np.add ufunc to add the 1D array to each row of the 2D array.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array of shape (3, 3) with random integers
array_2d = np.random.randint(0, 10, size=(3, 3))

# Create a 1D NumPy array with random integers
array_1d = np.random.randint(0, 10, size=3)

# Use the np.add ufunc to add the 1D array to each row of the 2D array
result_array = np.add(array_2d, array_1d)

# Print the original arrays and the resulting array
print('Original 2D array:\n', array_2d)
print('1D array:\n', array_1d)
print('Resulting array after adding 1D array to each row of 2D array:\n', result_array)

Output:

Original 2D array:
 [[5 1 0]
 [1 4 6]
 [7 5 6]]
1D array:
 [2 4 7]
Resulting array after adding 1D array to each row of 2D array:
 [[ 7  5  7]
 [ 3  8 13]
 [ 9  9 13]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named ‘array_2d’ with random integers ranging from 0 to 9 and a shape of (3, 3).
  • Create 1D NumPy Array:
    • Create a 1D NumPy array named ‘array_1d’ with random integers ranging from 0 to 9 and a length of 3.
  • Broadcasting with np.add:
    • Use the np.add "ufunc" to add the 1D array to each row of the 2D array. NumPy automatically broadcasts the 1D array to match the shape of the 2D array.
  • Print Results:
    • Print the original 2D array, the 1D array, and the resulting array after addition.

Python-Numpy Code Editor: