In-Place addition using np.add with the Out parameter in NumPy
NumPy: Universal Functions Exercise-16 with Solution
In-place ufunc Operations:
Write a NumPy program that uses np.add with the out parameter to perform in-place addition on a NumPy array.
Sample Solution:
Python Code:
import numpy as np
# Create a NumPy array
array_x = np.array([1, 2, 3, 4, 5])
# Create another array to add
array_y = np.array([10, 20, 30, 40, 50])
# Perform in-place addition using np.add with the out parameter
np.add(array_x, array_y, out=array_x)
# Print the resulting array
print("Resulting Array after In-Place Addition:")
print(array_x)
Output:
Resulting Array after In-Place Addition: [11 22 33 44 55]
Explanation:
- Import NumPy Library:
- Import the NumPy library to handle array operations.
- Create NumPy Arrays:
- Define two NumPy arrays 'array_x' and 'array_y' with example data.
- Perform In-Place Addition:
- Use np.add() with the out parameter to add 'array_y' to 'array_x' in-place, storing the result directly in 'array_x'.
- Finally print the resulting array to verify the in-place addition.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Comparing performance of custom ufunc and Python loop in NumPy.
Next: Handling NaN values in NumPy arrays using np.nan_to_num.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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/in-place-addition-using-np-dot-add-with-the-out-parameter-in-numpy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics