How to use the numpy.sign() method for 2D arrays in Python
The numpy.sign() method
The sign() method in Python’s NumPy library returns the sign of each number of the input array. It is done element-wise.
How does it work?
- If an element in the array
xis greater than0, the method returns1for that particular element. - If an element in the array
xis less than0, the method returns-1for that particular element. - If an element in the array
xis equal to0, the method returns0for that particular element. - For complex elements, if
x.real!= 0, thesign()method returnssign(x.real) + 0j. Otherwise, it returnssign(x.imag) + 0j.
Note: In Python, a list of lists can be used to generate a two-dimensional (2D) array.
Syntax
numpy.sign(x,out=None, where=True)
Parameters
x: This represents the input array.out: This specifies where the result is stored. This is an optional parameter.where: This represents the condition in which the input gets broadcasted. This is an optional parameter.
Return value
The numpy.sign() method returns the sign of each number of the input array.
Example
The following code demonstrates how to use the numpy.sign() method for 2D arrays.
# Import numpyimport numpy as np# Create 2D array using np.arrayx = np.array([[-7, -3.4 , 1.2 + 1j], [2, 3 + 1j, -9.5]])# Find the sign of each element in the array# Use np.sign()result = np.sign(x)print(result)
Explanation
- Line 2: We import the
numpylibrary. - Lines 4: We create a 2D array called
xconsisting of complex and non-complex elements. - Line 7: We use the
np.sign()method to compute the sign of each number of thexinput array. - Line 9: We print out the result.