Skip to main content
 首页 » 编程设计

python之如何设置不在矩阵子矩阵中的数字

2025年05月04日1898°冷暖

假设我有一个 numpy 数组。我想将 0 设置为不在子矩阵掩码中的索引。

import numpy as np 
 
mtrx = np.arange(25).reshape(5,5) 
mask = mtrx[1:4, 1:4] 

当然这是错误的:

mtrx[~mask] = 0 

我想要的结果:

[[ 0  0  0  0  0] 
 [ 0  6  7  8  0] 
 [ 0 11 12 13  0] 
 [ 0 16 17 18  0] 
 [ 0  0  0  0  0]] 

请您参考如下方法:

一种方法是索引一个零数组并添加索引的原始数组中的值:

s = np.s_[1:4,1:4] 
out = np.zeros_like(mtrx) 
out[s] = mtrx[s] 

print(out) 
 
array([[ 0.,  0.,  0.,  0.,  0.], 
       [ 0.,  6.,  7.,  8.,  0.], 
       [ 0., 11., 12., 13.,  0.], 
       [ 0., 16., 17., 18.,  0.], 
       [ 0.,  0.,  0.,  0.,  0.]])