划定一个numpy矩阵的区域

时间:2018-11-30 22:06:29

标签: python numpy matrix

我有一个560x560的numpy矩阵,我想将其转换为28x28的矩阵。
因此,我想将其细分为大小为16x16的区域,计算每个区域的平均值,然后将该值放入新的矩阵中。

现在我有

import numpy as np

oldMat = ...                      #I load the 560x560 matrix
newMat = np.zeros((28,28))        #Initializes the new matrix of size 28x28

for i in range(0,560, 16):
    for j in range(0,560, 16):    #Loops over the top left corner of each region 
        sum = 0
        for di in range(16):
            for dj in range(16):  #Loops over the indices of the elements in each region
                sum += oldMat[i+di, j+dj]

        mean = sum/256            #Calculates the mean of the elements of each region
        newMat[i][j] = mean


有更快的方法吗? (我确定有。)

1 个答案:

答案 0 :(得分:0)

如果您只是想从 Gene pLI Gene_Symbol Category ENSG00000063978: 6 Min. :0.000 U1 : 11 All eGenes : 8206 ENSG00000100012: 6 1st Qu.:0.000 Y_RNA : 7 All Genes :23790 ENSG00000204147: 6 Median :0.025 ASAH2B : 6 General : 2887 ENSG00000266338: 6 Mean :0.311 CCDC7 : 6 Postnatal : 1148 ENSG00000000938: 3 3rd Qu.:0.723 HERC2P2: 6 Postnatal (Non-specific): 479 ENSG00000000971: 3 Max. :1.000 MALAT1 : 6 Prenatal : 1653 (Other) :40172 NA's :14826 (Other):40160 Prenatal (Non-specific) : 2039 重塑矩阵,则可以使用2D --> 4D

np.reshape()

收益:

import numpy as np

np.random.seed(0)

data = np.random.randint(0,5,size=(6,6))

然后重塑:

[[4 0 3 3 3 1]
 [3 2 4 0 0 4]
 [2 1 0 1 1 0]
 [1 4 3 0 3 0]
 [2 3 0 1 3 3]
 [3 0 1 1 1 0]]

返回:

data.reshape((3,3,2,2))