Python numpy.compress()以减少矩阵

2024-09-30 20:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用vectorunumpy.compress()方法缩减NumPy矩阵,首先遍历行,然后遍历列。现在,我的代码如下所示:

n = 4 #number of rows/columns
square_matrix = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
u = np.array([1,0,1,0])

v = []

for i in range(n):
    v.append(np.compress(u,square_matrix[i]))

print(v)

我得到以下输出:

[array([1, 3]), array([5, 7]), array([ 9, 11]), array([13, 15])]

我有两个问题:

  1. 现在如何从输出中再次创建矩阵
  2. 我怎样才能对列重复相同的过程。(我最初的想法是使用u的转置,类似这样:
for j in range((len(v_matrix[0])-1)):
    w.append(np.compress(u.transpose(),v_matrix[:][j]))

Tags: 方法代码innumpyfornprange矩阵
2条回答

compress与许多numpy缩减函数一样,采用轴参数:

In [166]: np.compress(u,square_matrix, axis=1)
Out[166]: 
array([[ 1,  3],
       [ 5,  7],
       [ 9, 11],
       [13, 15]])
In [167]: np.compress(u,square_matrix, axis=0)
Out[167]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

按顺序应用压缩:

In [168]: np.compress(u,np.compress(u,square_matrix, axis=0),axis=1)
Out[168]: 
array([[ 1,  3],
       [ 9, 11]])

我没有意识到np.compress的存在,尽管从源文件来看,它一定从一开始就存在。布尔索引是相同的,而且更常见

In [169]: bu = u.astype(bool)
In [170]: square_matrix[bu,:]
Out[170]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])
In [171]: square_matrix[:,bu]
Out[171]: 
array([[ 1,  3],
       [ 5,  7],
       [ 9, 11],
       [13, 15]])

布尔索引相当于使用nonzero结果进行索引:

In [177]: np.nonzero(u)
Out[177]: (array([0, 2]),)
In [178]: idx = np.nonzero(u)[0]
In [179]: square_matrix[idx,:]
Out[179]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

并且可以同时应用于两个维度:

In [180]: square_matrix[idx[:,None],idx]
Out[180]: 
array([[ 1,  3],
       [ 9, 11]])

如果不进行重塑(使第一个列成为一列),我们将得到对角线:

In [181]: square_matrix[idx,idx]
Out[181]: array([ 1, 11])

并使用ix_实用程序:

In [185]: np.ix_(bu,bu)
Out[185]: 
(array([[0],
        [2]]),
 array([[0, 2]]))
In [186]: square_matrix[np.ix_(bu,bu)]
Out[186]: 
array([[ 1,  3],
       [ 9, 11]])
  1. How can I now create a matrix from the output again.

您可以以矢量化的方式执行该操作,只需为np.compress指定axis关键字

np.compress(u, square_matrix, axis=1)

输出:

array([[ 1,  3],
       [ 5,  7],
       [ 9, 11],
       [13, 15]])
  1. How could I repeat the same process for the columns. (My initial idea was to use a transpose of u)

您的建议是正确的,但是将矩阵替换为u。这将用行切换列

np.compress(u, square_matrix.T, axis=1)

输出:

array([[ 1,  9],
       [ 2, 10],
       [ 3, 11],
       [ 4, 12]])

相关问题 更多 >