简体   繁体   中英

How to create a sub-matrix in numpy

I have a two-dimensional NxM numpy array:

a = np.ndarray((N,M), dtype=np.float32)

I would like to make a sub-matrix with a selected number of columns and matrices. For each dimension I have as input either a binary vector, or a vector of indices. How can I do this most efficient?

Examples

a = array([[ 0,  1,  2,  3],
   [ 4,  5,  6,  7],
   [ 8,  9, 10, 11]])
cols = [True, False, True]
rows = [False, False, True, True]

cols_i = [0,2]
rows_i = [2,3]

result = wanted_function(a, cols, rows) or wanted_function_i(a, cols_i, rows_i)
result = array([[2,  3],
   [ 10, 11]])

You only need to makes cols and rows be a numpy array, and then you can just use the [] as:

import numpy as np

a = np.array([[ 0,  1,  2,  3],
   [ 4,  5,  6,  7],
   [ 8,  9, 10, 11]])

cols = np.array([True, False, True])
rows = np.array([False, False, True, True])

result = a[cols][:,rows]


print(result) 
print(type(result))
# [[ 2  3]
# [10 11]]
# <class 'numpy.ndarray'>

There are several ways to get submatrix in numpy:

In [35]: ri = [0,2]
    ...: ci = [2,3]
    ...: a[np.reshape(ri, (-1, 1)), ci]
Out[35]: 
array([[ 2,  3],
       [10, 11]])

In [36]: a[np.ix_(ri, ci)]
Out[36]: 
array([[ 2,  3],
       [10, 11]])

In [37]: s=a[np.ix_(ri, ci)]

In [38]: np.may_share_memory(a, s)
Out[38]: False

note that the submatrix you get is a new copy, not a view of the original mat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM