0

I have a numpy matrix of certain size (as an example let’s say we have a matrix 'A' which has 5 rows and 10 columns). I want to select a few columns out of this numpy matrix (let’s say I want to select rows 2,3,4,7, 9) and create another matrix (B).

For example,

import numpy as np
A = np.random.randint(5, size=(5, 10))
print A

[[1 3 2 1 2 1 0 2 2 2]
 [2 2 4 4 1 3 4 1 4 4]
 [2 4 1 3 0 4 3 0 1 0]
 [4 4 1 3 0 4 4 1 3 1]
 [1 0 1 2 1 0 4 0 1 3]]

The resulting matrix B should be:

B = [[2 1 2 2 2]
     [4 4 1 1 4]
     [1 3 0 0 0]
     [1 3 0 1 1]
     [1 2 1 0 3]]

What is the best way to do that?

Commoner
  • 1,678
  • 3
  • 19
  • 34
  • 3
    Do you mean columns? You can try: `B = A[:, [2,3,4,7,9]]` if rows, then `B = A[[2,3,4]]` – niraj Sep 24 '17 at 04:21
  • This question has an answer: https://stackoverflow.com/questions/4455076/how-to-access-the-ith-column-of-a-numpy-multidimensional-array/16121210#16121210, but I am not sure if this a duplicate. – Akavall Sep 24 '17 at 04:24
  • 1
    @0p3n5ourcE: Yes, I did mean columns. Sorry for the mistake. And, thanks very much for the reply. Your solution worked fantastically well. =) – Commoner Sep 24 '17 at 04:24
  • 1
    Great! glad it was helpful. – niraj Sep 24 '17 at 04:30

0 Answers0