Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I control matrix zero to be 1 by predetermined column in Python?

Suppose I have some list of column like this:

   res = [[2],[3, 4],[0],[5]]

Then, I need to change this zr zero matrix 4X4 to be 1 following column in res list above; For example: the first row plots 1 in column 2, the second row plots 1 in column 3 and 4, the third row will have no plot due to [0] and the fourth row plots 1 in column 5.

  zr = np.array([[0, 0, 0, 0, 0, 0,],
                 [0, 0, 0, 0, 0, 0,],
                 [0, 0, 0, 0, 0, 0,],
                 [0, 0, 0, 0, 0, 0 ]]

Target:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  zr = np.array([[0, 1, 0, 0, 0, 0,],
                 [0, 0, 1, 1, 0, 0,],
                 [0, 0, 0, 0, 0, 0,],
                 [0, 0, 0, 0, 1, 0 ]]

My current coding has a wrong change when some members in res equal to [0]:

for i, x in enumerate (res):
    if x==0:
        continue
    else:
        for j in x:
            zr[i][j-1] = 1

           

Do you have any suggestions? Thank You.

>Solution :

Here’s what you want to do. This will skip the line if it finds [0] as an inner list.

for i, x in enumerate (res):
    if x == [0]: 
        continue
    else:
        for j in x:
            zr[i][j-1] = 1

print(zr)

Output:

[[0 1 0 0 0 0]
 [0 0 1 1 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 1 0]]

What you were doing wrong is you were trying to compare x (which is a list) with 0. That’s always False.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading