Home > OS >  Duplicate every nth row and column of a numpy array
Duplicate every nth row and column of a numpy array

Time:11-16

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:

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?

CodePudding user response:

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]])
  • Related