1

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!

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! This is really helpful.
1

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

2 Comments

Thank you so much! This is a really helpful tool.
It may be worth noting that even though you may set values in the original array while accessing it through Boolean Indexing, this same Boolean Indexing notation cannot be used to store a view of the original array in a variable. Instead the variable will become a copy of this view. See this answer: stackoverflow.com/a/47671637
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.