Skip to main content
 首页 » 编程设计

python之使用 numpy 过滤值

2025年05月04日20soundcode

我有一个 numpy 零矩阵并且大小 = (4, 8)

x = [[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, 0 , 0, 0, 0, 0, 0],] 

此外,我有三个不同的矩阵。

a = [[1, 1, 1 , 1, 1, 1, 1, 1], 
     [1, 1, 1 , 1, 1, 1, 1, 1], 
     [1, 1, 1 , 1, 1, 1, 1, 1], 
     [1, 1, 1 , 1, 1, 1, 1, 1],] 
 
b = [[2, 2, 2 , 2, 2, 2, 2, 2], 
     [2, 2, 2 , 2, 2, 2, 2, 2], 
     [2, 2, 2 , 2, 2, 2, 2, 2], 
     [2, 2, 2 , 2, 2, 2, 2, 2],]  
 
c = [[3, 3, 3 , 3, 3, 3, 3, 3], 
     [3, 3, 3 , 3, 3, 3, 3, 3], 
     [3, 3, 3 , 3, 3, 3, 3, 3], 
     [3, 3, 3 , 3, 3, 3, 3, 3],] 

我想得到如下结果

output = [[1, 2, 1, 2, 1, 2, 1, 2], 
          [2, 3, 2, 3, 2, 3, 2, 3], 
          [1, 2, 1, 2, 1, 2, 1, 2], 
          [2, 3, 2, 3, 2, 3, 2, 3],] 

矩阵a的值出现在(第0行,第2行)和(第0列,第2列,第4列,第6列)

矩阵b的值出现在第0行、第1行、第2行、第3行,但第0行和第2行的值2出现在第1列、第3列、第3列5, column 7, next in the row 1 and row 3 the value 2 appears in the column 0, column 2, column 4, column 6

矩阵c的值出现在(row 1, row 3) and (column 1, column 3, column 5, column 7)

import numpy as np 
h, w = x.shape 
output = np.zeros((h, w)) 
 
for i in range(h): 
    for j in range(w): 
        if (i % 2) == 0 and (j % 2) == 0: 
            output[i, j] = a[i, j] 
        elif (i % 2) == 1 and (j % 2) == 1: 
            output[i, j] = c[i, j] 
        else: 
            output[i, j] = b[i, j] 
print(output) 
'''   
output = [[1. 2. 1. 2. 1. 2. 1. 2.] 
          [2. 3. 2. 3. 2. 3. 2. 3.] 
          [1. 2. 1. 2. 1. 2. 1. 2.] 
          [2. 3. 2. 3. 2. 3. 2. 3.]] 
''' 

我想尽量不用for循环,可以用numpy解决吗?

请您参考如下方法:

你可以使用np.choose:

y,x = np.ogrid[:4,:8] 
np.choose((y&1)+(x&1),[a,b,c]) 
# array([[1, 2, 1, 2, 1, 2, 1, 2], 
#        [2, 3, 2, 3, 2, 3, 2, 3], 
#        [1, 2, 1, 2, 1, 2, 1, 2], 
#        [2, 3, 2, 3, 2, 3, 2, 3]])