Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

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

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

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

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

Keep Exploring
Related Courses