如何在numpy中创建子矩阵 [英] How to create a sub-matrix in numpy

查看:83
本文介绍了如何在numpy中创建子矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维NxM 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?

示例

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

推荐答案

有几种方法可以在numpy中获取子矩阵:

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.

这篇关于如何在numpy中创建子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆