Python Numpy 数组扩展 repeat和tile

singer 2019-12-07

numpy.repeat

官方文档

numpy.repeat(a, repeats, axis=None)
Repeat elements of an array.

可以看出repeat函数是操作数组中的每一个元素,进行元素的复制。
例如:

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

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

numpy.tile

官方文档

numpy.tile(A, reps)
Construct an array by repeating A the number of times given by reps.

可以看出tile函数是将数组A作为操作对象
例如:

>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> np.tile(a, 2)
array([[1, 2, 1, 2],
       [3, 4, 3, 4]])

>>> a = [[0,1], [2,3], [4,5]]
>>> x = np.tile(a, (2,1))
>>> x
array([[0, 1],
       [2, 3],
       [4, 5],
       [0, 1],
       [2, 3],
       [4, 5]])

相关推荐