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?

4
  • 3
    Do you mean columns? You can try: B = A[:, [2,3,4,7,9]] if rows, then B = A[[2,3,4]] Commented Sep 24, 2017 at 4:21
  • This question has an answer: stackoverflow.com/questions/4455076/…, but I am not sure if this a duplicate. Commented Sep 24, 2017 at 4:24
  • 1
    @0p3n5ourcE: Yes, I did mean columns. Sorry for the mistake. And, thanks very much for the reply. Your solution worked fantastically well. =) Commented Sep 24, 2017 at 4:24
  • 1
    Great! glad it was helpful. Commented Sep 24, 2017 at 4:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.