Home > Mobile >  Numpy use specific rows and columns to form a new matrix
Numpy use specific rows and columns to form a new matrix

Time:09-26

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
i = np.array([True, False, True])
j = np.array([True, True, False])
print(a[i, j])
print(a[i, :][:, j])

The first print:

[1 8]

The second print:

[[1 2]
 [7 8]]

What I want is the second one. Is there a better way than a[i, :][:, j]?

I feel this is not the correct way.

CodePudding user response:

The indices need to be reshaped. See the second example at Purely integer array indexing

# Either q[i[:, np.newaxis], j] or a[np.ix_(i, j)]
# or a[i[:, None], j]
print(a[np.ix_(i, j)])

CodePudding user response:

You don't need the extra columns for i, just use:

print(a[i][:, j])

Output:

[[1 2]
 [7 8]]
  • Related