Python 删除数组里全为零的行或者列

发布于 2023-01-12  589 次阅读


Please refresh the page if equations are not rendered correctly.
---------------------------------------------------------------

import numpy as np
Array= np.array([[4, 1, 1, 2, 0, 4],
                   [3, 4, 3, 1, 0, 4],
                   [1, 4, 3, 1, 0, 0],
                   [0, 4, 4, 0, 0, 3],
                   [0, 0, 0, 0, 0, 0]])
Array==0
array([[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]])
(Array==0).all()
False

1.删除全为零的行或者列

1.1 全为零的行

(Array==0).all(axis=1)#行
Array.any(axis=1)==0
array([False, False, False, False,  True])
Array[~Array.any(axis=1)==0]
array([[4, 1, 1, 2, 0, 4],
       [3, 4, 3, 1, 0, 4],
       [1, 4, 3, 1, 0, 0],
       [0, 4, 4, 0, 0, 3]])
Array[~(Array==0).all(axis=1)]
array([[4, 1, 1, 2, 0, 4],
       [3, 4, 3, 1, 0, 4],
       [1, 4, 3, 1, 0, 0],
       [0, 4, 4, 0, 0, 3]])

1.2 全为零的列

对于列的操作需要对数组进行转置

(Array==0).all(axis=0)#列
array([False, False, False, False,  True, False])
Array.any(axis=0)==0
array([False, False, False, False,  True, False])
(Array.T[~(Array.T).any(axis=1)==0]).T
array([[4, 1, 1, 2, 4],
       [3, 4, 3, 1, 4],
       [1, 4, 3, 1, 0],
       [0, 4, 4, 0, 3],
       [0, 0, 0, 0, 0]])
Everything not saved will be lost.
最后更新于 2023-01-12