'Extracting multiple sets of rows/ columns from a 2D numpy array
I have a 2D numpy array from which I want to extract multiple sets of rows/ columns.
# img is 2D array
img = np.arange(25).reshape(5,5)
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
I know the syntax to extract one set of row/ column. The following will extract the first 4 rows and the 3rd and 4th column as shown below
img[0:4, 2:4]
array([[ 2, 3],
[ 7, 8],
[12, 13],
[17, 18]])
However, what is the syntax if I want to extract multiple sets of rows and/or columns? I tried the following but it leads to an invalid syntax
error
img[[0,2:4],2]
The output that I am looking for from the above command is
array([[ 2],
[12],
[17]])
I tried searching for this but it only leads to results for one set of rows/ columns or extracting discrete rows/ columns which I know how to do, like using np.ix.
For context, the 2D array that I am actually dealing with has the dimensions ~800X1200, and from this array I want to extract multiple ranges of rows and columns in one go. So something like img[[0:100, 120:210, 400, 500:600], [1:450, 500:550, 600, 700:950]]
.
Solution 1:[1]
IIUC, you can use numpy.r_
to generate the indices from the slice:
img[np.r_[0,2:4][:,None],2]
output:
array([[ 2],
[12],
[17]])
intermediates:
np.r_[0,2:4]
# array([0, 2, 3])
np.r_[0,2:4][:,None] # variant: np.c_[np.r_[0,2:4]]
# array([[0],
# [2],
# [3]])
Solution 2:[2]
You can create your slices with numpy.r_
:
np.r_[0:2, 4]
# array([0,1,4])
Then you can get the specific rows and columns as follows:
rows = np.r_[0:2, 4]
cols = np.r_[0, 2:4]
img[rows][:, cols]
# array([[ 0, 2, 3],
# [ 5, 7, 8],
# [20, 22, 23]])
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 | mozway |
Solution 2 | Tobias Molenaar |