Home > Software engineering >  set values of 2D numpy array by parameters
set values of 2D numpy array by parameters

Time:04-21

I need to create 2D np array by the known shape and parameters in this way:

import numpy as np
rows = 9
cols = 8
xrows = 3
xcols = 2

the wanted results:

([[ 1,  1,  4,  4,  7,  7, 10, 10],
    [ 1,  1,  4,  4,  7,  7, 10, 10],
    [ 1,  1,  4,  4,  7,  7, 10, 10],
    [ 2,  2,  5,  5,  8,  8, 11, 11],
    [ 2,  2,  5,  5,  8,  8, 11, 11],
    [ 2,  2,  5,  5,  8,  8, 11, 11],
    [ 3,  3,  6,  6,  9,  9, 12, 12],
    [ 3,  3,  6,  6,  9,  9, 12, 12],
    [ 3,  3,  6,  6,  9,  9, 12, 12]])
rows%xrows = 0
cols%xcols = 0 

rows is the number of rows of the array, cols is the number of columns of the array, xrows is the number of rows in each slice, xcols is the number of column in each slice. the answer should be general not for this parameters

CodePudding user response:

IIUC, you can use:

((np.arange(rows//xrows*cols//xcols, dtype=int) 1)
 .reshape((rows//xrows,cols//xcols), order='F')
 .repeat(xrows,0)
 .repeat(xcols,1)
 )

Output:

array([[ 1,  1,  4,  4,  7,  7, 10, 10],
       [ 1,  1,  4,  4,  7,  7, 10, 10],
       [ 1,  1,  4,  4,  7,  7, 10, 10],
       [ 2,  2,  5,  5,  8,  8, 11, 11],
       [ 2,  2,  5,  5,  8,  8, 11, 11],
       [ 2,  2,  5,  5,  8,  8, 11, 11],
       [ 3,  3,  6,  6,  9,  9, 12, 12],
       [ 3,  3,  6,  6,  9,  9, 12, 12],
       [ 3,  3,  6,  6,  9,  9, 12, 12]])
  • Related