2

I have a source array:

a = array([[1, 1, 2, 2],
           [3, 4, 5, 6],
           [7, 7, 7, 8]])

And a vector that indicates how many times I want to tile each row of the array:

count = array([3, 1, 2])

I want to get:

results =array([[1, 1, 2, 2],
                [1, 1, 2, 2],
                [1, 1, 2, 2],
                [3, 4, 5, 6],
                [7, 7, 7, 8],
                [7, 7, 7, 8]]

Is there a vectorized/numpy way to achieve this?

Currently I'm using an iterative loop approach and it's horribly slow when len(a) and/or count contains high values.

1 Answer 1

1

numpy.repeat() is what you are after:

Code:

np.repeat(a, count, axis=0)

Test Code:

import numpy as np

a = np.array([[1, 1, 2, 2],
              [3, 4, 5, 6],
              [7, 7, 7, 8]])

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

print(np.repeat(a, count, axis=0))

Results:

[[1 1 2 2]
 [1 1 2 2]
 [1 1 2 2]
 [3 4 5 6]
 [7 7 7 8]
 [7 7 7 8]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.