how to duplicate each row of a matrix N times Numpy
Asked Answered
A

3

18

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.

Aura answered 10/11, 2018 at 13:5 Comment(3)
Can you please edit your sample data, right now it does not make much sense.Sabbat
I think your example a should be a = [[2, 3], [5, 6], [7, 9]].Kiln
I've posted a picture I hope will make it clear :) a is a column arrayAura
U
21

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]]
Urbai answered 10/11, 2018 at 13:9 Comment(0)
W
3

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]]
Weathers answered 29/7, 2022 at 20:53 Comment(0)
P
0

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.]]
Promulgate answered 10/11, 2018 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.