w3resource

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

NumPy: Universal Functions Exercise-3 with Solution

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:

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

Previous: Compute Square Root of each element using np.sqrt in NumPy.
Next: Element-wise Multiplication of 2D arrays using np.multiply in NumPy.

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://198.211.115.131/python-exercises/numpy/add-1d-array-to-each-row-of-2d-array-using-np-dot-add-in-numpy.php