numpy 在Python中标识数组中已删除的行和列

iszxjhcz  于 2023-02-12  发布在  Python
关注(0)|答案(2)|浏览(142)

我有一个数组A1,我正在删除零行和零列,但我还想确定删除了哪一行和哪一列,我给出了当前输出和预期输出。

import numpy as np

        
A1=np.array([[0, 1, 2],
            [0, 0, 0],
            [0, 3, 4]])

mask = A1!= 0
A2 = A1[np.ix_(mask.any(1), mask.any(0))]
print([A2])

当前输出为

[array([[1, 2],
       [3, 4]])]

预期输出为

[array([[1, 2],
       [3, 4]])]
[1] where 1 is the deleted row, 
[0] where 0 is the deleted column
fbcarpbf

fbcarpbf1#

这是获得所需输出的代码:

import numpy as np

A1=np.array([[0, 1, 2],
            [0, 0, 0],
            [0, 3, 4]])

mask = A1 != 0
deleted_rows = np.where(~mask.any(axis=1))[0]
deleted_columns = np.where(~mask.any(axis=0))[0]
A2 = A1[np.ix_(mask.any(1), mask.any(0))]

print([A2])
print("Deleted rows:", deleted_rows)
print("Deleted columns:", deleted_columns)
    • 结果:**
array([[1, 2],
       [3, 4]])]
Deleted rows: [1]
Deleted columns: [0]
o2rvlv0m

o2rvlv0m2#

如果删除的行和列具有相同的值(在本例中为0),则可以执行以下操作:

deletedrows = [i for i in range(A1.shape[0]) if np.all(A1[i] == 0)]
deletedcolumns = [i for i in range(A1.T.shape[0]) if np.all(A1.T[i] == 0)]

相关问题