w3resource

Create a custom ufunc in NumPy to Add 10 to each element

NumPy: Universal Functions Exercise-1 with Solution

Basic ufunc Creation:

Write a Numpy program that creates a custom ufunc that adds 10 to every element in a NumPy array. Use this ufunc on a 1D array of integers.

Sample Solution:

Python Code:

import numpy as np

# Define a custom ufunc that adds 10 to each element
def add_ten(x):
    return x + 10

# Create a ufunc from the custom function using np.frompyfunc
add_ten_ufunc = np.frompyfunc(add_ten, 1, 1)

# Create a 1D NumPy array of integers
array_1d = np.array([1, 2, 3, 4, 5])

# Apply the custom ufunc to the 1D array
result_array = add_ten_ufunc(array_1d)

# Print the original array and the resulting array
print('Original 1D array:', array_1d)
print('Resulting array after applying add_ten_ufunc:', result_array)

Output:

Original 1D array: [1 2 3 4 5]
Resulting array after applying add_ten_ufunc: [11 12 13 14 15]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Define Custom Function:
    • Define a custom function add_ten that takes input x and returns x + 10.
  • Create ufunc:
    • Create a ufunc from the custom function using "np.frompyfunc". The function takes the custom function, the number of input arguments (1), and the number of output arguments (1).
  • Create 1D NumPy Array:
    • Created a 1D NumPy array named array_1d with integers [1, 2, 3, 4, 5].
  • Apply Custom ufunc:
    • Apply the custom ufunc “add_ten_ufunc()” to the 1D array to obtain the result.
  • Print Results:
    • Print the original 1D array and the resulting array after applying the custom "ufunc".

Python-Numpy Code Editor:

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

Previous: NumPy Universal Functions Home.
Next: Compute Square Root of each element using np.sqrt 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/create-a-custom-ufunc-in-numpy-to-add-10-to-each-element.php