1

given a matrix A, e.g. A = np.array([[1,2,3,4],[5,6,7,8]]) and two lists one of row indices and one of column indices, e.g. row=(0,1), column=(0,2) I want to extract the corresponding rows and columns of matrix A in python, so in this example I want the result to be np.array([[1, 3], [5,7])). I know how to adress a single entry in a matrix, but not all within a list, moreover I am always loosing the structure. So far the best result I got was with A[row, column], which does not return all indices listed, only A=np.array(([1,7])). I also know that there exists a slicing command, but this only works for consecutive rows and columns which is not the case.

Thank you very much in advance!

samabu
  • 181
  • 6

2 Answers2

2

It looks like you want:

A[np.array(row)[:,None], column]

output:

array([[1, 3],
       [5, 7]])

intermediate:

np.array(row)[:,None]

array([[0],
       [1]])
mozway
  • 194,879
  • 13
  • 39
  • 75
1
np.array([[A[r][c] for c in column] for r in row]) # array([[1, 3], [5, 7]])
remarcoble
  • 537
  • 1
  • 4
  • 19
  • 1
    two drawbacks, as you loop this will be slow on large arrays, and you cannot use this to index/assign the existing array, this creates a new one ;) – mozway Jun 13 '22 at 11:04