扩大数组并填充价值?

Enlarging array and filling with value?

扩大 numpy 一维数组并用最后一个值填充新的 space 的最佳方法是什么。

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 )

你可以使用 numpy pad,像这样:

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

另一种方法:

b = np.ones(5, dtype=a.dtype)*a[-1]
b[:len(a)] = a

输出:

[1 2 3 3 3]