suppose I have this function:
a = np.array([-2,1,-5,2])
if a <0:
a += 10
print (a)
why I am getting this error.
If I pass only one value then it is okey. How to solve this problem?
thank you in advance.
suppose I have this function:
a = np.array([-2,1,-5,2])
if a <0:
a += 10
print (a)
why I am getting this error.
If I pass only one value then it is okey. How to solve this problem?
thank you in advance.
numpy
does element wise comparison and addition and is vectorized. A direct translation of if-else
in numpy
is np.where()
:
import numpy as np
a = np.where(a < 0, a + 10, a)
# array([8, 1, 5, 2])
You can simply increment by indexing with a boolean array (a < 0
):
a[a < 0] += 10