how to duplicate each row of a matrix N times Numpy

Question:

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.

Asked By: ggg

||

Answers:

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]]
Answered By: Space Impact

To create an empty multidimensional array in NumPy (e.g. a 2D array m*n to store your matrix), in case you don’t know m how many rows you will append and don’t care about the computational cost Stephen Simmons mentioned (namely re-building the array at each append), you can squeeze to 0 the dimension to which you want to append to: X = np.empty(shape=[0, n]).

This way you can use for example (here m = 5 which we assume we didn’t know when creating the empty matrix, and n = 2):

import numpy as np

n = 2
X = np.empty(shape=[0, n])

for i in range(5):
    for j  in range(2):
        X = np.append(X, [[i, j]], axis=0)

print X

which will give you:

[[ 0.  0.]
 [ 0.  1.]
 [ 1.  0.]
 [ 1.  1.]
 [ 2.  0.]
 [ 2.  1.]
 [ 3.  0.]
 [ 3.  1.]
 [ 4.  0.]
 [ 4.  1.]]
Answered By: Mohammad reza Kashi

If your input is a vector, use atleast_2d first.

a = np.atleast_2d([2, 3]).repeat(repeats=3, axis=0)
print(a)

# [[2 3]
#  [2 3]
#  [2 3]]
Answered By: Muhammad Yasirroni
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.