Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Duplicate every nth row and column of a numpy array

I have a given 2d np-array and want to duplicate every e.g. 3rd row and column.

Basically, if I had an np-array

a = np.array([
  [1, 2, 3, 1, 2, 3],
  [2, 3, 4, 2, 3, 4],
  [3, 4, 5, 3, 4, 5],
  [4, 5, 6, 4, 5, 6]
])

I would want to produce:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b = np.array([
  [1, 2, 3, 3, 1, 2, 3, 3],
  [2, 3, 4, 4, 2, 3, 4, 4],
  [3, 4, 5, 5, 3, 4, 5, 5],
  [3, 4, 5, 5, 3, 4, 5, 5],
  [4, 5, 6, 6, 4, 5, 6, 6]
])

How could I do that?

>Solution :

rows

You can identify the Nth row using arithmetic, then duplicate it with np.repeat:

N = 3

out = np.repeat(a, (np.arange(a.shape[0])%N == (N-1)) + 1, axis=0)

Output:

array([[1, 2, 3, 1, 2, 3],
       [2, 3, 4, 2, 3, 4],
       [3, 4, 5, 3, 4, 5],
       [3, 4, 5, 3, 4, 5],
       [4, 5, 6, 4, 5, 6]])

intermediate:

(np.arange(a.shape[0])%N == (N-1)) + 1
# array([1, 1, 2, 1])

rows and cols

same mechanisms on both dimensions:

N = 3

rows = (np.arange(a.shape[0])%N == (N-1)) + 1
# array([1, 1, 2, 1])
cols = (np.arange(a.shape[1])%N == (N-1)) + 1
# array([1, 1, 2, 1, 1, 2])

out = np.repeat(np.repeat(a, rows, axis=0), cols, axis=1)

output:

array([[1, 2, 3, 3, 1, 2, 3, 3],
       [2, 3, 4, 4, 2, 3, 4, 4],
       [3, 4, 5, 5, 3, 4, 5, 5],
       [3, 4, 5, 5, 3, 4, 5, 5],
       [4, 5, 6, 6, 4, 5, 6, 6]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading