0

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

1
  • 2
    could you be more specific on what each parameter is defining? Commented Apr 20, 2022 at 15:39

1 Answer 1

2

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

I can use that, but better if it possible to tune the slices by column not by rows
@user18628648 sure, that was an oversight, see update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.