如何在NumPy中重排矩阵列以构造[单位矩阵|剩余矩阵]形式
Great question! Let's walk through how to solve this problem—since there isn't a direct NumPy built-in function that does exactly this column rearrangement, but we can put together a simple, effective solution ourselves.
Step-by-Step Approach
The core idea is straightforward:
- Identify identity columns: Locate which columns form the identity submatrix (each column is a standard unit vector, with exactly one
1in a unique row and0s elsewhere). - Reorder columns: Move these identity columns to the leftmost positions, followed by all remaining columns in their original order.
Implementation Code
Let's start with your initial matrix, then add the full rearrangement logic:
import numpy as np # Your original input matrix _list = [[1,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0,-1, 1,-1], [0, 0, 0, 0, 0, 0, 1,-1, 1, 0, 0]] matrix = np.array(_list) print("Original Matrix:") print(matrix) print('==' * 50) def get_identity_column_indices(matrix): n_rows = matrix.shape[0] identity_indices = [] # For each row, find the column that acts as its unit vector for row_idx in range(n_rows): for col_idx in range(matrix.shape[1]): # Check if this column has 1 in the current row, 0 in all other rows if matrix[row_idx, col_idx] == 1 and np.all(matrix[np.arange(n_rows) != row_idx, col_idx] == 0): identity_indices.append(col_idx) break return identity_indices # Get indices of identity columns and remaining non-identity columns identity_cols = get_identity_column_indices(matrix) remaining_cols = [col for col in range(matrix.shape[1]) if col not in identity_cols] # Rearrange the matrix columns rearranged_matrix = matrix[:, identity_cols + remaining_cols] print("Rearranged Matrix (Identity | Residue):") print(rearranged_matrix)
Does a NumPy Built-in Function Exist?
Unfortunately, there's no direct NumPy function that handles this exact task. NumPy offers tools like np.identity to create identity matrices, or linear algebra functions for inversion/decomposition, but nothing purpose-built to rearrange columns of an existing matrix to extract an identity submatrix on the left.
That said, our custom solution is efficient given your problem constraints (you confirmed an identity submatrix definitely exists), and it's easy to adapt if your matrix dimensions change later.
Key Notes
- This code assumes the identity submatrix has the same number of rows as your input matrix (matching your example: 4 rows → 4-column identity submatrix).
- Since you guaranteed an identity submatrix exists, we don't include error handling for missing unit vectors—you can add checks if you need to handle edge cases in the future.
内容的提问来源于stack exchange,提问作者Álvaro Navarro Torres

