Python:如何从 numpy 中的矩阵中消除所有零行

标签 python numpy

我有一个 0 和 1 的 numpy 数组。 我需要在一个 pythonic move 中提取所有由全 0 组成的行,并保留其余部分。

我已经寻找过以前的问题来回答这个问题,看来 这个问题是这个的重复: Remove all-zero rows in a 2D matrix

但我不明白任何答案。看起来重要的命令是这样的:

a[~(a==0).all(1)]

但我完全不明白它是如何提取矩阵的。事实上,当我在代码中使用这一行时,它会提取一个数组,而不是二维矩阵。

我看过np.all() explanation , 但看起来这只是一个测试。

谁能帮帮我。

最佳答案

与代码行 a[~(a==0).all(1)] 相关的主要问题是它适用于 numpy.array并且您似乎正在使用 numpy.matrix,代码无法正常工作。如果 anumpy.matrix,请改用 a[~(a==0).all(1).A1].

由于您是 numpy 的新手,我将指出复杂的单行代码可以通过将它们分解为单个步骤并打印中间结果来更好地理解。这通常是调试的第一步。我将为 a[~(a==0).all(1)] 行对 numpy.arraynumpy.matrix< 执行此操作.

对于numpy.array:

In [1]: from numpy import *

In [2]: a = array([[4, 1, 1, 2, 0, 4],
                   [3, 4, 3, 1, 4, 4],
                   [1, 4, 3, 1, 0, 0],
                   [0, 4, 4, 0, 4, 3],
                   [0, 0, 0, 0, 0, 0]])

In [3]: print a==0
[[False False False False  True False]
 [False False False False False False]
 [False False False False  True  True]
 [ True False False  True False False]
 [ True  True  True  True  True  True]]

In [6]: print (a==0).all(1)
[False False False False  True]

In [7]: print ~(a==0).all(1)
[ True  True  True  True False]

In [8]: print a[~(a==0).all(1)]
[[4 1 1 2 0 4]
 [3 4 3 1 4 4]
 [1 4 3 1 0 0]
 [0 4 4 0 4 3]]

对于 numpy.matrix:

In [1]: from numpy import *

In [2]: a = matrix([[4, 1, 1, 2, 0, 4],
                    [3, 4, 3, 1, 4, 4],
                    [1, 4, 3, 1, 0, 0],
                    [0, 4, 4, 0, 4, 3],
                    [0, 0, 0, 0, 0, 0]])

In [3]: print a==0
[[False False False False  True False]
 [False False False False False False]
 [False False False False  True  True]
 [ True False False  True False False]
 [ True  True  True  True  True  True]]


In [5]: print (a==0).all(1)
[[False]
 [False]
 [False]
 [False]
 [ True]]

In [6]: print (a==0).all(1).A1
[False False False False  True]

In [7]: print ~(a==0).all(1).A1
[ True  True  True  True False]

In [8]: print a[~(a==0).all(1).A1]
[[4 1 1 2 0 4]
 [3 4 3 1 4 4]
 [1 4 3 1 0 0]
 [0 4 4 0 4 3]]

In[5] 的输出显示了为什么这不起作用:(a==0).all(1) 产生一个二维结果,它不能t 用于索引行。因此,我只是在下一行添加了 .A1 以将其转换为 1D。

Here是关于数组和矩阵之间差异的一个很好的答案。此外,我将添加一次 infix operator被完全采用,使用 numpy.matrix 几乎没有优势。此外,由于大多数人在他们的代码中使用 numpy.array 来表示矩阵,他们通常会将 numpy.array 描述为“矩阵”,从而在术语。

最后,顺便说一句,我会注意到以上所有内容都是在 ipython 中完成的从命令行。 IPython 是此类工作的绝佳工具。

关于Python:如何从 numpy 中的矩阵中消除所有零行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673095/

相关文章:

python - 如何使用numpy生成楼梯编号序列

python - 在工作节点上安装 SPARK 模块

python - ndarray 的浅拷贝到函数

python - 如何为 PyYAML 编写代表?

python - pip install 与 python3 -m pip install

python - 递归阶乘计算器 RecursionError

python - 将不同的 Keras 模型合并为一个

python - 为我的 Django 项目中的每个应用程序创建自定义 404 错误?

python - 为 concurrent.futures.ProcessPoolExecutor 播种 numpy.random 的 default_rng 和 SeedSequence 对象

python - 减去下一行使用当前行,python 数据框