Classify real values by sign
Convert numeric arrays into directional indicators for thresholding or categorical logic.
NumPy · Function
Returns the sign of each input element. Real values become -1, 0, or 1; complex values are divided by their magnitude, and NaN inputs remain NaN.
As a universal function, np.sign processes each input element independently. Real values map to -1, 0, or 1 according to whether they are negative, zero, or positive; complex values are normalized by their magnitude, while NaN inputs produce NaN.
numpy.sign(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True [, signature])| Name | Type | Description |
|---|---|---|
x | array_like | Input value or array whose signs are evaluated. |
out | ndarray or None | Optional output array receiving the result. |
where | array_like of bool | Condition selecting where computation occurs. |
casting | {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional | Casting rule applied to inputs. |
order | {‘K’, ‘A’, ‘C’, ‘F’}, optional | Memory layout order for the output. |
dtype | dtype, optional | Output data type. |
subok | bool, optional | Whether subclasses are passed through. |
signature | str or tuple of ints, optional | Optional generalized-ufunc signature. |
An ndarray containing the sign of x, or a scalar when x is scalar.
import numpy as np
x = np.array([-5.0, 0.0, 4.5, 3 - 4j, 8j])
print(np.sign(x))
# [-1. +0.j 0. +0.j 1. +0.j 0.6-0.8j 0. +1.j ]Computes the sign of real and complex values element by element.
Convert numeric arrays into directional indicators for thresholding or categorical logic.
Normalize complex values to unit magnitude while preserving their phase.
Propagate undefined numeric inputs through sign-based calculations.
np.sign is an element-wise universal function. For real x, it returns -1 when x is below zero, 0 when x equals zero, and 1 when x is above zero.
Follow-up: How does it handle complex numbers? It returns x divided by abs(x), with zero remaining zero.
NaN inputs produce NaN. This preserves the undefined sign of NaN rather than classifying it as positive, negative, or zero.
Follow-up: What happens for a scalar NaN? The result is a scalar NaN because scalar inputs yield scalar outputs.
For complex inputs, np.sign returns the input normalized by its magnitude, x / abs(x), and returns zero when x is zero. For example, 3-4j becomes 0.6-0.8j.
Follow-up: Why does 8j become 1j? Its magnitude is 8, so dividing 8j by 8 yields 1j.
numpy.absolutenumpy.copysignnumpy.heavisidenumpy.signbit