更新时间:2022-12-09 21:02:44
带遮罩的矢量化方法-
def remove_vectorized(a):
mask = a==0
m_row = ~mask.all(1)
m_col = ~mask.all(0)
comb_mask = m_row | m_col
return a[comb_mask][:,comb_mask] #or a[np.ix_(comb_mask, comb_mask)]
示例运行
案例1:
In [485]: a
Out[485]:
array([[0, 0, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
In [486]: remove_vectorized(a)
Out[486]:
array([[1, 1],
[0, 0]])
案例2:
In [489]: a
Out[489]:
array([[0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0]])
In [490]: remove_vectorized(a)
Out[490]:
array([[0, 1, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 1, 0]])