python - 有没有办法智能地删除零行以获得 python 中的方矩阵?

标签 python numpy matrix

在线性代数中,Determinant是一个标量值,可以根据方阵的元素计算,并对矩阵描述的线性变换的某些属性进行编码。

要计算行列式,需要切割矩阵的某些行或列。

例如矩阵A

A = np.array([[1,1],[2,2],[0,0]])
A
array([[1, 1],
       [2, 2],
       [0, 0]])

需要剪切最后一行

B = A[:2]
B
array([[1, 1],
       [2, 2]])

然后,行列式操作可用。

np.linalg.det(B)
0.0

另一个矩阵需要切割的是列而不是行

C = A.T
C
array([[1, 2, 0],
       [1, 2, 0]])

所以,切行或切列是不确定的,有没有办法在python中智能地去除零行得到一个方阵?

最佳答案

要删除全为零的行或列(即选择具有任何非零值的行或列),您可以使用以下命令。

A = np.array([[1, 2],
               [0, 0],
               [4, 5]])
B_rows = A[(A != 0).any(1), :]  # Remove rows that are all zero.
>>> B_rows
array([[1, 2],
       [4, 5]])

A = np.array([[1, 2, 0],
               [3, 4, 0]])
B_cols = A[:, (A != 0).any(0)]  # Remove columns that are all zero.
>>> B_cols
array([[1, 2],
       [3, 4]])

关于python - 有没有办法智能地删除零行以获得 python 中的方矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998194/

相关文章:

python - 无法让我的 else 语句在 while 循环中打印

python - 如何有效结合类设计和矩阵数学?

matlab - 矩阵创建Octave/Matlab,无循环解决方案请求

c++ - 如何将非常量 int 作为模板参数传递?

java - 在java中手动为opengl创建 View (lookat)矩阵

python - Lambda 不支持 NLTK 文件大小

c++ - 从 C++ 线程调用 python 脚本,GIL

python - 在 seaborn 中创建海盗图(箱形图和点图的组合)

python - 如何使用多个索引从 NumPy 数组中获取值

python - Scikit 学习高斯 HMM : ValueError: startprob must sum to 1. 0