Efficiently test matrix rows and columns with numpy

前端 未结 2 446
囚心锁ツ
囚心锁ツ 2021-01-24 16:18

I am trying to remove both the row i and column i when both the row i and column i contains all 0s. For example in this case we can see that row 0 is all zeros

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-24 16:42

    One thing you can do- evaluate the boolean matrix "matrix == 0" outside of your for loop, and use that matrix instead of reevaluating it every run.

    It'd be something like:

    def remove(matrix):
        binary_matrix = matrix == 0
        for i, x in reversed(list(enumerate(matrix))):
            if np.all(binary_matrix , axis=0)[i] and np.all(binary_matrix , axis=1)[i]:
                matrix = np.delete(matrix,i,axis=0)
                matrix = np.delete(matrix,i,axis=1)
                binary_matrix = np.delete(binary_matrix ,i,axis=0)
                binary_matrix = np.delete(binary_matrix ,i,axis=1)
        return matrix
    

提交回复
热议问题