Slice numpy array wth list of wanted rows

arrays, numpy, python, slice

Solution

Use `take()`:

In [87]: m = np.random.random((6, 2))

In [88]: m
Out[88]: 
array([[ 0.6641412 ,  0.31556053],
       [ 0.11480163,  0.00143887],
       [ 0.4677745 ,  0.43055324],
       [ 0.49749099,  0.15678506],
       [ 0.48024596,  0.65701218],
       [ 0.48952677,  0.97089177]])

In [89]: m.take([0, 2, 5], axis=0)
Out[89]: 
array([[ 0.6641412 ,  0.31556053],
       [ 0.4677745 ,  0.43055324],
       [ 0.48952677,  0.97089177]])

Problem

I have a numpy 2d array `A`, and a list of row numbers `row_set`. How can I get new array `B` such as if `row_set = [0, 2, 5]`, then `B = [A_row[0], A_row[2], A_row[5]]`? I thought of something like this: ``` def slice_matrix(A, row_set): slice = array([row for row in A if row_num in row_set]) ``` but I don't have any idea, how can I get a row_num.

Original source