我想使用vectoru
和numpy.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])]
我有两个问题:
u
的转置,类似这样:for j in range((len(v_matrix[0])-1)):
w.append(np.compress(u.transpose(),v_matrix[:][j]))
compress
与许多numpy
缩减函数一样,采用轴参数:按顺序应用压缩:
我没有意识到
np.compress
的存在,尽管从源文件来看,它一定从一开始就存在。布尔索引是相同的,而且更常见布尔索引相当于使用
nonzero
结果进行索引:并且可以同时应用于两个维度:
如果不进行重塑(使第一个列成为一列),我们将得到对角线:
并使用
ix_
实用程序:您可以以矢量化的方式执行该操作,只需为
np.compress
指定axis
关键字输出:
您的建议是正确的,但是将矩阵替换为
u
。这将用行切换列输出:
相关问题 更多 >
编程相关推荐