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)
user1304846
  • 415
  • 2
  • 5
  • 13

3 Answers3

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)
Andrew Guy
  • 9,310
  • 3
  • 28
  • 40
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

Back2Basics
  • 7,406
  • 2
  • 32
  • 45
  • 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. – Andrew Guy Jun 21 '16 at 02:34
  • 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) – Back2Basics Jun 21 '16 at 02:38
  • 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. – Andrew Guy Jun 21 '16 at 03:06
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.

tschundler
  • 2,098
  • 1
  • 14
  • 15
  • 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]] – user1304846 Jun 21 '16 at 02:25