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

NumpyServer Side ProgrammingProgramming

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...\n", arr)

Get the type of the array −

print("\nOur Array type...\n", arr.dtype)

Get the dimensions of the Array −

print("\nOur Array Dimension...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

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

print("\nResult...\n",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...\n", arr)

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimension...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# To return an element-wise indication of the sign of a number, use the numpy.sign() method in Python Numpy
print("\nResult...\n",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.]
raja
Updated on 08-Feb-2022 09:55:11

Advertisements