How To Change Element In 2d Array In Python
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 some
Solution 1:
You need to use the indices of b
to change elements, not the elements themselves. Try:
import numpy as np
b = np.array([[Truefor j inrange(5)] for i inrange(5)])
print(b)
for i, r inenumerate(b):
for j, c inenumerate(r):
b[i,j] = Falseprint(b)
Solution 2:
You could use broadcasting in Numpy. (works on all elements without the for loops.)
a =np.array([True]*25).reshape(5,5)
b = a * Falseprint(b)
True evaluates to 1 and False evaluates to 0 so 1*0 is ... 0
Solution 3:
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.
Post a Comment for "How To Change Element In 2d Array In Python"