0

I intend to change the value of boolean array in 2D from True to false, but the code does not work. The output results are the same even I use statement b[r][c] = False. Could someone help me on this, thanks.

import numpy as np

b = np.array([[True for j in range(5)] for i in range(5)])
print(b)

for r in b:
    for c in r:
        b[r][c] = False
print(b)

3 Answers 3

3

You need to use the indices of b to change elements, not the elements themselves. Try:

import numpy as np

b = np.array([[True for j in range(5)] for i in range(5)])
print(b)

for i, r in enumerate(b):
    for j, c in enumerate(r):
        b[i,j] = False
print(b)
Sign up to request clarification or add additional context in comments.

2 Comments

And it's worth noting b[i, j] is a little more efficient given how numpy works.
Yep, you're right, I've edited my answer to change b[i][j] to b[i,j].
1

You could use broadcasting in Numpy. (works on all elements without the for loops.)

a =np.array([True]*25).reshape(5,5)
b = a * False
print(b)

True evaluates to 1 and False evaluates to 0 so 1*0 is ... 0

3 Comments

This is a better answer than mine as far as efficient implementation goes, but OP should also understand how to properly edit a list/array from within a for loop.
I'm of the mindset that we need to abolish the for loop in libraries like numpy and pandas and so forth in that direction on the stack. (This is a theory in progress so I'm looking for counter examples)
I appreciate being able to substitute a normal list for a numpy array and know that I don't have to reformat code that uses that list in a for loop. If speed is a concern, then I can do some code reformatting.
0

What you're looking for is this:

b[r, c] = False

numpy arrays work best using numpy's access methods. The other way would create a view of the array and you'd be altering the view.

EDIT: also, r, c do need to be numbers, not True / True like the other answer said. I was reading more into the question than was being asked.

1 Comment

This one does not work completely. See the result [[False False True True True] [ True False True True True] [False False True True True] [False False True True True] [False False True True True]]

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.