NumPy: Compute an element-wise indication of the sign for all elements in a given array
NumPy Mathematics: Exercise-41 with Solution
Write a NumPy program to compute an element-wise indication of the sign for all elements in a given array.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array x
x = np.array([1, 3, 5, 0, -1, -7, 0, 5])
# Displaying the original array x
print("Original array;")
print(x)
# Using np.sign() to find the sign of each element in array x
r1 = np.sign(x)
# Creating a copy of array x and modifying it to assign signs manually
r2 = np.copy(x)
r2[r2 > 0] = 1 # If element is positive, set it to 1
r2[r2 < 0] = -1 # If element is negative, set it to -1
# Comparing the results obtained from np.sign() and manually assigning signs
assert np.array_equal(r1, r2)
# Displaying the element-wise indication of the sign for all elements of the array using np.sign()
print("Element-wise indication of the sign for all elements of the said array:")
print(r1)
Sample Output:
Original array; [ 1 3 5 0 -1 -7 0 5] Element-wise indication of the sign for all elements of the said array: [ 1 1 1 0 -1 -1 0 1]
Explanation:
x = np.array([1, 3, 5, 0, -1, -7, 0, 5]): This line initializes a one-dimensional NumPy array x.
r1 = np.sign(x): The np.sign(x) returns an array of the same shape as x, where each element has a value of -1, 0, or 1, depending on whether the corresponding element in x is negative, zero, or positive, respectively.
r2 = np.copy(x): This line creates a new copy of the input array x.
r2[r2 > 0] = 1: This line modify the copy such that all positive elements in x are replaced with 1.
r2[r2 < 0] = -1: This line modify the copy such that all negative elements are replaced with -1.
assert np.array_equal(r1, r2): Here, the assert statement checks whether r1 and r2 are equal NumPy arrays. If they are not equal, an AssertionError is raised. If they are equal, the program continues to execute. As r1 and r2 are equal assert returns True.
Python-Numpy Code Editor:
Previous: Write a NumPy program to compute xy, element-wise where x, y are two given arrays.
Next: NumPy DateTime Exercises Home.
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://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-41.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics