How to replicate a row of an array with numpy?

前端 未结 2 1949
醉梦人生
醉梦人生 2021-01-27 00:26

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]])         


        
相关标签:
2条回答
  • 2021-01-27 00:53

    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]])
    
    0 讨论(0)
  • 2021-01-27 00:55

    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

    0 讨论(0)
提交回复
热议问题