CSforStructuralEngineer - 7 months ago 24

Python Question

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

`numpy.sign`

Answer

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.)