2

I want to replicate the last row of an array in python and found the following lines of code in the numpy documentation

>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, [1, 2], axis=0)

in the above code what does the second parameter "[1,2]" in np.repeat do? if i want to replicate a row in a 3*3 array how will this second parameter change.

2
  • Second argument of repeat specify how many times each element should be repeated. Can you provide your sample output? I would be much easier to provide an answer if output is there Commented Dec 24, 2017 at 13:33
  • Dark's answer nicely elaborate the behaviour of np.repeat. However you should also have a look at np.tile and decide how you are willing to repeat rows. Commented Dec 24, 2017 at 13:45

2 Answers 2

6

It's the repeats parameter

repeats : int or array of ints

The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

It's the number of times you want to repeat a row or column based on the parameter axis.

x = np.array([[1,2],[3,4],[4,5]])
np.repeat(x, repeats = [1, 2, 1 ], axis=0)

This would lead to repetition of row 1 once, row 2 twice and row 3 once.

array([[1, 2],
       [3, 4], 
       [3, 4],
       [4, 5]])

Similarly, if you specify the axis = 1. Repeats can take maximum of 2 elements in the list,and below code lead to repetition of column 1 once and column 2 twice.

x = np.array([[1,2],[3,4],[4,5]])
np.repeat(x, repeats = [1, 2 ], axis=1)

array([[1, 2, 2],
       [3, 4, 4],
       [4, 5, 5]])

If you want to repeat only last row, repeat only last row and stack i.e

rep = 2
last = np.repeat([x[-1]],repeats= rep-1 ,axis=0)

np.vstack([x, last])

array([[1, 2],
       [3, 4],
       [4, 5],
       [4, 5]])
Sign up to request clarification or add additional context in comments.

1 Comment

I have another question suppose i have a very large array say 100*100 then if i want to replicate the last row how would i do so would it be like [1,1,1,1....2] or is there a shorter way of doing so?
2

I have test it using following code

    >>> a
    array([[1, 2],
           [3, 4]])
    >>> np.repeat(a, [2,3], axis = 0)
    array([[1, 2],
           [1, 2],
           [3, 4],
           [3, 4],
           [3, 4]])
    >>> np.repeat(a, [1,3], axis = 0)
    array([[1, 2],
           [3, 4],
           [3, 4],
           [3, 4]])

The second parameter seems mean how many times the i-th elements in a will be repeat. As my code shown above, [2,3] repeats a[0] 2 times and repeats a[1] 3 times, [1,3] repeats a[0] 1 times and repeats a[1] 3 times

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.