You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用numpy.compress()缩减NumPy矩阵:行缩减后重构矩阵及列缩减实现方案问询

解决你的NumPy矩阵缩减问题

Hey there! Let's tackle your two NumPy questions step by step—they're common operations once you get the hang of how NumPy handles array axes.

1. 把行缩减后的输出重构为矩阵

Right now, your v variable is a list of 1D NumPy arrays. Since each of these arrays is the same length (2, in your case), you can just wrap the whole list in np.array() to convert it into a proper 2D matrix:

import numpy as np

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

# Your original row compression code
v = []
for i in range(n):
    v.append(np.compress(u, square_matrix[i]))

# Convert the list of arrays to a 2D matrix
v_matrix = np.array(v)
print(v_matrix)

Running this will give you a clean 2D matrix output:

[[ 1  3]
 [ 5  7]
 [ 9 11]
 [13 15]]

As a side note, you can simplify your row compression code to avoid the loop entirely. Using boolean indexing (converting u to a boolean array) or using np.compress() with the axis parameter does the same thing in one line:

# Option 1: Boolean indexing
v_matrix = square_matrix[:, u.astype(bool)]

# Option 2: Using np.compress with axis=1 (matches your original approach)
v_matrix = np.compress(u, square_matrix, axis=1)

2. 对矩阵的列执行缩减操作

Your initial thought to use a transpose is on the right track, but there's a small mistake in your code snippet: v_matrix[:][j] doesn't get the j-th column—it actually gets the j-th row (since v_matrix[:] returns the full matrix, and adding [j] indexes the rows).

Luckily, np.compress() makes column compression straightforward with the axis parameter. Just set axis=1 to tell NumPy to compress along the column axis:

# Compress columns directly on the original matrix
column_compressed_matrix = np.compress(u, square_matrix, axis=1)
print(column_compressed_matrix)

This will output the same result as your row-compressed matrix:

[[ 1  3]
 [ 5  7]
 [ 9 11]
 [13 15]]

If you want to compress columns on your already row-compressed v_matrix, the same logic applies:

# Compress columns of the row-compressed matrix
v_column_compressed = np.compress(u, v_matrix, axis=1)
print(v_column_compressed)

And if you still want to test the transpose approach (just for learning), here's how to do it correctly:

# Transpose the matrix, compress rows, then transpose back
column_compressed_via_transpose = np.compress(u, square_matrix.T, axis=1).T
print(column_compressed_via_transpose)

This will also give you the correct column-compressed matrix.


内容的提问来源于stack exchange,提问作者euler132

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 12:27:31