2
\$\begingroup\$

I'm trying to find a way to know if a number on a matrix is positive, negative or zero. Below is my code, but I'm wondering if there is a more Pythonic way to write that. Any ideas?

array = np.random.randint(-10,10, size=(10,10))

def function(array):
    case1 = np.where(array < 0, -1, array)
    case2 = np.where(case1 > 0, 1, case1)
    case3 = np.where(case2 == 0, 0, case2)
    return case3

print(function(array))
\$\endgroup\$
5
\$\begingroup\$

You should choose better functions names, function does not give any indication what the purpose of the function is.

In addition, a docstring comment can be used to give a short description.

But actually there is no need for a custom function because numpy.sign already provides the exact functionality:

Returns an element-wise indication of the sign of a number.

Example:

import numpy as np

array = np.random.randint(-10,10, size=(4,4))
print(np.sign(array))

Output:

[[-1  1  1  1]
 [ 1  1  0  0]
 [ 1  1 -1  1]
 [ 1 -1  1 -1]]
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Yes, that's it! Thanks! \$\endgroup\$ – Connie Jun 28 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.