CSforStructuralEngineer CSforStructuralEngineer - 1 month ago 5x
Python Question

Convert a numpy array into an array of signs with 0 as positive

I have a large numpy array with positive data, negative data and 0s. I want to convert it to an array with the signs of the current values such that 0 is considered positive. If I use

it returns 0 if the current value is 0 but I want something that returns 1 instead. Is there an easy way to do this?


If x is the array, you could use 2*(x >= 0) - 1.

x >= 0 will be an array of boolean values (i.e. False and True), but when you do arithmetic with it, it is effectively cast to an array of 0s and 1s.

You could also do np.sign(x) + (x == 0). (Note that np.sign(x) returns floating point values, even when x is an integer array.)