Skip to content Skip to sidebar Skip to footer

Fast Numpy Way To Repeat (vertically) Each Half Of 2d Array

Assuming we have the following 2D array: In [200]: a = np.arange(8).reshape(4,2) In [201]: a Out[201]: array([[0, 1], [2, 3], [4, 5], [6, 7]]) How may repeat

Solution 1:

Reshape to split the first axis into two giving us a 3D array, then repeat along the first and finally reshape back to 2D -

np.repeat(a.reshape(-1,2,2),2,axis=0).reshape(-1,2)

Generalizing it -

def repeat_blocks(a):
    N = a.shape[0]
    B = N//2 # Block length
    R = 2# number of repeatsout = np.repeat(a.reshape(N//B,B,-1),R,axis=0).reshape(N*R,-1)returnout

Sample runs -

Case #1 :

In [120]: a
Out[120]: 
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])

In [121]: repeat_blocks(a)
Out[121]: 
array([[0, 1],
       [2, 3],
       [0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [4, 5],
       [6, 7]])

Case #2 :

In [123]: a
Out[123]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

In [124]: repeat_blocks(a)
Out[124]: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [ 6,  7],
       [ 8,  9],
       [10, 11]])

Post a Comment for "Fast Numpy Way To Repeat (vertically) Each Half Of 2d Array"