pythonnumpymatrixduplicatesrow

How to duplicate each row of a matrix N times Numpy


I have a matrix with these dimensions (150,2) and I want to duplicate each row N times. I show what I mean with an example.

Input:

a = [[2, 3], [5, 6], [7, 9]]

suppose N= 3, I want this output:

[[2 3]
 [2 3]
 [2 3]
 [5 6]
 [5 6]
 [5 6]
 [7 9]
 [7 9]
 [7 9]]

Thank you.


Solution

  • Use np.repeat with parameter axis=0 as:

    a = np.array([[2, 3],[5, 6],[7, 9]])
    
    print(a)
    [[2 3]
     [5 6]
     [7 9]]
    
    r_a = np.repeat(a, repeats=3, axis=0)
    
    print(r_a)
    [[2 3]
     [2 3]
     [2 3]
     [5 6]
     [5 6]
     [5 6]
     [7 9]
     [7 9]
     [7 9]]