user14655550
user14655550

Reputation:

how to repeat the elements of a 2d array n times without converting it to a list?

I have an array of a = np.array([[1,2],[3,4]]) I am looking for a way to repeat each element for a certain times (lets say 3 times) to get the following array

b = [[1  2]
     [1  2]
     [1  2]
     [3  4]
     [3  4]
     [3  4]]

Is there a function to do this in numpy array directly or should I convert it to a list and multiply it and again convert it into an array?

Upvotes: 1

Views: 798

Answers (2)

Nerveless_child
Nerveless_child

Reputation: 1408

You could try this:

a = np.array([[1,2],[3,4]])

n_repeat = 3
b = np.tile(a, n_repeat).reshape(-1, a.shape[1])

Upvotes: 0

fountainhead
fountainhead

Reputation: 3722

This should do it:

b = np.repeat(a, 3, axis=0)

Upvotes: 1

Related Questions