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

Printing specific rows of an array in Python

I am trying specific rows of the array A based on the list J. For instance, it should print 1st and 4th rows of A since J=[[1,4]] and append as shown in the expected output. I also present the current output.

import numpy as np

A=np.array([[1,2,3,4,5],
            [6,7,8,9,10],
            [11,12,13,14,15],
            [16,17,18,19,20],
            [21,22,23,24,25]])


J=[[1, 4]]

for i in J[0]:
     A=A[i]
     print([A])

The current output is

[array([ 6,  7,  8,  9, 10])]
[array(10)]

The expected output is

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

[array([[ 6,  7,  8,  9, 10],
        [21,22,23,24,25]])]

>Solution :

Can do in one line:

np.array([list(A[i]) for i in J[0]])

#output
array([[ 6,  7,  8,  9, 10],
       [21, 22, 23, 24, 25]])

if you want to append to a list then:

l=[]
l.append(np.array([list(A[i]) for i in J[0]]))

#output
[array([[ 6,  7,  8,  9, 10],
       [21, 22, 23, 24, 25]])]
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