1

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

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

3 Answers 3

1

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]])]
Sign up to request clarification or add additional context in comments.

Comments

1

The issue is that you are re-writing your A array within your loop with A=A[i], so when the code tries to find A[i] the second time, it will be filtering on the new A which is the row from the previous loop (hence the output of 10). Pick a different letter to use here like this:

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

Output:

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

To get your exact output of a list containing an array containing nested lists, you can create an empty list C, and add the list of B each loop then turn that into an array in a list at the end rather than printing each step, like this:

C = []
for i in J[0]:
    B=A[i]
    C += [list(B)]
C = [np.array(C)]

Now C is:

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

3 Comments

desired output is [array([[ 6, 7, 8, 9, 10],[21,22,23,24,25]])]
@YashMehta have added a second section
now it is perfect..!
0

Define an empty array variable and append desired raw arrays inside the loop and after finishing print out this array.

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

O/P will be:

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

Update You can use filter numpy by indices

J = [[1, 4]]
B = A[J[0]]
print([B])

O/P will be:

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

2 Comments

see the desired output..!
@YashMehta Check my update about using filter numpy array by indices, You are welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.