'How to extract non-consecutive rows and columns of a matrix?
How do I extract from a matrix rows and columns that are not consecutive. For example, in this matrix how do i extract rows 1,2 and 4 with columns 1, 2 and 4?
import numpy as np
a = np.matrix([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[18, 19, 20, 21, 22]])
So the new matrix should be:
b = ([[7, 8 , 10],
[12, 13, 15],
[19, 20, 22]])
Solution 1:[1]
In the doc section linked by hpaulj, see example starting with From a 4x3 array the corner elements should be selected using advanced indexing.
Specifically, the paragraph that starts This broadcasting can also be achieved using the function ix_:
In your case, rows are [1, 2, 4] and same for columns, so
rows = np.array([1, 2, 4], dtype=np.intp)
columns = np.array([1, 2, 4], dtype=np.intp)
b = a[np.ix_(rows, columns)]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ToolmakerSteve |
