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!
CodePudding user response:
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]])
CodePudding user response:
np.array([[A[r][c] for c in column] for r in row]) # array([[1, 3], [5, 7]])