5

I need to select multiple different values from each row of a 2D array.

A = np.array([[ 1, 2, 3, 4],
              [ 5, 6, 7, 8],
              [ 9,10,11,12])
A[something]

>>> np.array([[ 1, 2],
              [ 6, 7],
              [11,12]])

I know I can create a boolean array the same shape as A and set each element in a for loop, but I'm hoping come up with a better solution.

1
  • 1
    What have you tried? Can you clarify a bit more on what it is you're trying to do?
    – cs95
    Jun 10, 2018 at 20:57

1 Answer 1

9

You can try the following:

import numpy as np
A = np.array([[ 1, 2, 3, 4],
              [ 5, 6, 7, 8],
              [ 9,10,11,12]])
i = [[0],[1],[2]]
j = [[0,1], [1,2],[2,3]]
B = A[i,j]
print(B)
#Prints
[[ 1  2]
 [ 6  7]
 [11 12]]

Example run

2
  • This is exactly what I wanted, thank you! I had already tried with i=[0,1,2]. Do you mind explaining why the first has to be 2D?
    – phsyron
    Jun 10, 2018 at 21:24
  • 3
    i should be (3,1) shape to broadcast with the (3,2) shape of j.
    – hpaulj
    Jun 11, 2018 at 1:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.