Search code examples
pythonarraysnumpyresizefill

Enlarging array and filling with value?


What is the best way to enlarge a numpy 1D array and fill the new space with the last value.

F.e.

 a = [1,2,3]
 ... enlarge ..to size 5 ...
 a = [1,2,3,3,3]

    vals = list(seq)
    vals.extend( [seq[-1]] * diff )
    seq = np.array(vals )

Solution

  • You can use numpy pad, like this:

    import numpy as np
    
    N = 10
    a = np.array([1,2,3])
    
    a = np.pad(a, (0, N-len(a)), 'edge')
    
    # array([1, 2, 3, 3, 3, 3, 3, 3, 3, 3])