0
votes

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

3 Answers

3
votes

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)
1
votes

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

0
votes

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.