How to properly select an area inside a numpy ndarray

Viewed 27

How to properly select a specific area inside a NumPy ndarray. For example, in the sample code below I want to select the 2x3 matrix that corresponds to the intersections of columns and rows of matrix M stored in a and b respectively,

M = np.random.rand(4,5)
print(M)
a = [0, 2]
b = [0, 2, 3]
Selection = M[a,b]

but I am getting:

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (3,)

when I want from matrix M:

[[0.36899449 0.02531732 0.04966994 0.66058884 0.26193009]
 [0.92893864 0.10193024 0.74850916 0.72822403 0.09112129]
 [0.28863096 0.45470087 0.01032583 0.30931807 0.42765045]
 [0.59819051 0.94057773 0.95352287 0.81818564 0.24220261]]

To get:

[[0.36899449 0.04966994]
 [0.28863096 0.01032583]
 [0.59819051 0.95352287]]
0 Answers
Related