Reputation: 1277
I have a numpy and a boolean array:
nparray = [ 12.66 12.75 12.01 13.51 13.67 ]
bool = [ True False False True True ]
I would like to replace all the values in nparray
by the same value divided by 3 where bool
is False.
I am a student, and I'm reasonably new to python indexing. Any advice or suggestions are greatly appreciated!
Upvotes: 1
Views: 3956
Reputation: 31532
With just python you can do it like this:
nparray = [12.66, 12.75, 12.01, 13.51, 13.67]
bool = [True, False, False, True, True]
map(lambda x, y: x if y else x/3.0, nparray, bool)
And the result is:
[12.66, 4.25, 4.003333333333333, 13.51, 13.67]
Upvotes: 0
Reputation: 16079
naming an array bool might not be the best idea. As ayhan did try renaming it to bl or something else.
You can use numpy.where see the docs here
nparray2 = np.where(bl == False, nparray/3, nparray)
Upvotes: 2
Reputation:
Use boolean indexing
with ~
as the negation operator:
arr = np.array([12.66, 12.75, 12.01, 13.51, 13.67 ])
bl = np.array([True, False, False, True ,True])
arr[~bl] = arr[~bl] / 3
array([ 12.66 , 4.25 , 4.00333333, 13.51 , 13.67 ])
Upvotes: 1