Python - List Of Same Columns / Rows From Matrix
I have a matrix A, and a list of indices, say l = [0,3,4,5]. Is there an easy way to access the 4x4 submatrix of A corresponding to those rows and columns, i.e. A[l,l]? A[l,:] acce
Solution 1:
IIUC, you can use np.ix_
:
>>> A = np.arange(100).reshape(10,10)
>>> L = [0,3,4,5]
>>> np.ix_(L, L)
(array([[0],
[3],
[4],
[5]]), array([[0, 3, 4, 5]]))
>>> A[np.ix_(L, L)]
array([[ 0, 3, 4, 5],
[30, 33, 34, 35],
[40, 43, 44, 45],
[50, 53, 54, 55]])
This can be used to index in for modification purposes as well:
>>> A[np.ix_(L, L)] *= 10
>>> A[np.ix_(L, L)]
array([[ 0, 30, 40, 50],
[300, 330, 340, 350],
[400, 430, 440, 450],
[500, 530, 540, 550]])
Of course, if you'd prefer, you can always construct the arrays returned by ix_
manually:
>>> Larr = np.array(L)
>>> Larr[:,None]
array([[0],
[3],
[4],
[5]])
>>> Larr[None, :]
array([[0, 3, 4, 5]])
Solution 2:
If you're using numpy (you should), you can do this
import numpy as np
m=np.reshape(range(36),(6,6))
ix=(0,3,4,5)
m[ix,:][:,ix]
array([[ 0, 3, 4, 5],
[18, 21, 22, 23],
[24, 27, 28, 29],
[30, 33, 34, 35]])
Post a Comment for "Python - List Of Same Columns / Rows From Matrix"