Trusted answers to developer questions
Trusted Answers to Developer Questions

RELATED TAGS

python3
numpy
python

How to use the numpy.sign() method for 2D arrays in Python

Maria Elijah

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 x is greater than 0, the method returns 1 for that particular element.
  • If an element in the array x is less than 0, the method returns -1 for that particular element.
  • If an element in the array x is equal to 0, the method returns 0 for that particular element.
  • For complex elements, if x.real!= 0, the sign() method returns sign(x.real) + 0j. Otherwise, it returns sign(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 numpy
import numpy as np
# Create 2D array using np.array
x = 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 numpy library.
  • Lines 4: We create a 2D array called x consisting of complex and non-complex elements.
  • Line 7: We use the np.sign() method to compute the sign of each number of the x input array.
  • Line 9: We print out the result.

RELATED TAGS

python3
numpy
python
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2