How to create a sub-matrix in numpy

久未见 提交于 2021-01-28 01:12:43

问题


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]])

回答1:


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.




回答2:


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'>


来源:https://stackoverflow.com/questions/24241834/how-to-create-a-sub-matrix-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!