1

I have a 2d numpy array, matrix_a, shaped 2x20. How do I select columns 5:8 and columns 15:18.

matrix_a = np.array([[1,2,3,4,5...,19,20],
                     [1,2,3,4,5...,19,20]])

I want to select:

    [[5,6,7,15,16,17],
     [5,6,7,15,16,17]]

I can select the columns separately using matrix_a[0,5:8], is there a way to select it all at once?

Barring 0-index vs 1-index, in MATLAB, all I would have to do is:

matrix_a(:,[5:8, 15:18])

Is there an analogous, simple command in python?

0

1 Answer 1

4

You can use numpy.r_ to combine the two slices, which is a convenient way to Translate slice objects to concatenation along the first axis. And it can accept mixed lists, arrays, scalars and slice notation, e.g. np.r_[5, np.array([1,2]), [3]*2, 15:18] is a validation construction as well, which gives array([ 5, 1, 2, 3, 3, 15, 16, 17]):

matrix_a = np.tile(np.arange(1, 21), 2).reshape(2, 20)

matrix_a[:, np.r_[5:8, 15:18]]
#array([[ 6,  7,  8, 16, 17, 18],
#       [ 6,  7,  8, 16, 17, 18]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.