How to replicate a row of an array with numpy?

前端 未结 2 1952
醉梦人生
醉梦人生 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]])
    

提交回复
热议问题