How can I select a small matrix from a larger matrix by its index

时间:2019-01-18 18:32:17

标签: python

I have a larger 2 dimensional matrix which is 36*72 and I want to select a small matrix from it by using indexes.

The matrix looks like this:

[ [312, 113, 525, 543, ...] , 
  [...],
  [...],
   ... ].

And I print the shape like this:

print(array(matrix).shape)
(36, 72)

But when I try to print out the small matrix like this

print(matrix[6:9][9])

The error is "IndexError: list index out of range"

Then I tried

print(matrix[6:9,9])

It showed "TypeError: list indices must be integers, not tuple"

Then I tried

print(matrix[6:9][8:9])

I get the empty list. But when I tried

print(matrix[9][9])

It did give out some number.

2 个答案:

答案 0 :(得分:1)

对于numpy数组,您可以使用非常方便的索引方法,这是numpy部分的功能,其中的部分被称为 fancy indexing
让我们用一个小的二维数组示例进行尝试:

import numpy as np
a=np.arange(48).reshape(6, 8)
print(a)
#[[ 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 25 26 27 28 29 30 31]                                
# [32 33 34 35 36 37 38 39]                                 
# [40 41 42 43 44 45 46 47]]             

如果您现在想索引,例如第2和3行以及第3至6列,无论是使用常量还是变量,您都可以将其简单地写下来:

r1 = 2; r2 = 4
print(a[r1:r2, 3:7])
#[[19 20 21 22]                                               
# [27 28 29 30]]            

您可能想在这里进一步阅读:https://docs.scipy.org/doc/numpy/user/basics.indexing.html

答案 1 :(得分:0)

Here's an example. I have a 3x3 matrix, named 'a' and I want to select the top left 2x2 matrix named 'c'.

>>> import numpy as np # importing numpy
>>> a=np.matrix('1 2 3;4 5 6;7 8 9') # creating an example matrix, named a
>>> a
matrix([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
>>> b=[[a.item(0,0),a.item(0,1)],[a.item(1,0),a.item(1,1)]] # creating a list, with 1,1 1,2 2,1 and 2,2 indices of a. remember, in math indexing starts from 1 but in most programming languages, it starts from 0
>>> b
[[1, 2], [4, 5]]
>>> c=np.matrix(b) # creating an numpy matrix object from b which is a part of a
>>> c
matrix([[1, 2],
        [4, 5]])