如何在numpy中创建子矩阵

时间:2014-06-16 10:41:28

标签: python numpy multidimensional-array indexing

我有一个二维NxM numpy数组:

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

我想制作一个具有选定数量的列和矩阵的子矩阵。对于每个维度,我输入二进制向量或索引向量。我怎样才能最有效率?

实施例

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

2 个答案:

答案 0 :(得分:2)

您只需将colsrows设为一个numpy数组,然后您就可以使用[]作为:

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

答案 1 :(得分:2)

有几种方法可以在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

请注意,您获得的子矩阵是新副本,而不是原始垫子的视图。