简体   繁体   中英

Cannot modify numpy 2d array

I am trying to modify the boolarr numpy array depending on the contents of the reducedMatrix array. It is supposed to change the boolean value of the boolarr to False if reducedMatrix is not a 0 or a -1.

reducedMatrix = np.load(reducedweightmatrix)

boolarr = np.ones(shape=(len(reducedMatrix),len(reducedMatrix)),dtype="bool")

for y,yelement in enumerate(reducedMatrix):
    for x,xelement in enumerate(yelement):
        if(xelement != -1 and xelement != 0):
            print(x)
            print(y)
            print("\n")
            boolarr[y,x] == False

print(reducedMatrix)
print(boolarr)

The log keeps on showing the following:

[[-1  5  5  0  0]
 [ 5 -1  0  0  0]
 [ 5  0 -1  0  5]
 [ 0  0  0 -1  0]
 [ 0  0  5  0 -1]]
[[ True  True  True  True  True]
 [ True  True  True  True  True]
 [ True  True  True  True  True]
 [ True  True  True  True  True]
 [ True  True  True  True  True]]

What am I doing wrong?

You need to change

boolarr[y,x] == False

into

boolarr[y,x] = False

There is no need to edit boolarray elementwise when you can just create it in one vectorized line:

boolarray = (reducedMatrix == 0) | (reducedMatrix == -1)
# array([[ True, False, False,  True,  True],
#        [False,  True,  True,  True,  True],
#        [False,  True,  True,  True, False],
#        [ True,  True,  True,  True,  True],
#        [ True,  True, False,  True,  True]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM