Return an element-wise indication of the sign of a number in Numpy


To return an element-wise indication of the sign of a number, use the numpy.sign() method in Python Numpy.

The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs. For complex inputs, the sign function returns sign(x.real) + 0j if x.real != 0 else sign(x.imag) + 0j.

The complex(nan, 0) is returned for complex nan inputs. There is more than one definition of sign in common use for complex numbers. The definition used here is equivalent to x/x*x which is different from a common alternative, x/|x|.

Steps

At first, import the required library −

import numpy as np

Create an array with float type using the array() method −

arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])

Display the array −

print("Array...
", arr)

Get the type of the array −

print("
Our Array type...
", arr.dtype)

Get the dimensions of the Array −

print("
Our Array Dimension...
",arr.ndim)

Get the shape of the Array −

print("
Our Array Shape...
",arr.shape)

To return an element-wise indication of the sign of a number, use the numpy.sign() method −

print("
Result...
",np.sign(arr))

Example

import numpy as np

# Create an array with float type using the array() method
arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To return an element-wise indication of the sign of a number, use the numpy.sign() method in Python Numpy print("
Result...
",np.sign(arr))

Output

Array...
[ 50.8 120.3 200.7 -320.1 -450.4 0. ]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result...
[ 1. 1. 1. -1. -1. 0.]

Updated on: 08-Feb-2022

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements