w3resource

In-Place addition using np.add with the Out parameter in NumPy


16. Ufunc In-Place Addition Using Out Parameter

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to perform in-place addition on an array using np.add with the out parameter and then verify the original array is modified.
  • Write a Numpy program to use np.add with out to add two arrays and store the result in one of the input arrays, ensuring type consistency.
  • Write a Numpy program to chain in-place additions on an array using np.add with the out parameter and then confirm the cumulative effect.
  • Write a Numpy program to implement conditional in-place addition using np.add with the out parameter and a boolean mask.

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.



Follow us on Facebook and Twitter for latest update.