numpy.tile
语法
numpy.tile(A,reps)
作用
Construct an array by repeating A the number of times given by reps.
If
reps
has lengthd
, the result will have dimension of
max(d, A.ndim)
.If
A.ndim < d
,A
is promoted to be d-dimensional by prepending new
axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
or shape (1, 1, 3) for 3-D replication. If this is not the desired
behavior, promoteA
to d-dimensions manually before calling this
function.If
A.ndim > d
,reps
is promoted toA
.ndim by pre-pending 1’s to it.
Thus for anA
of shape (2, 3, 4, 5), areps
of (2, 2) is treated as
(1, 1, 2, 2).Note : Although tile may be used for broadcasting, it is strongly
recommended to use numpy’s broadcasting operations and functions.
通过按照reps
给定的次数,repeat数组A
,构造一个新的数组。
新的数组的维度数取决于A.ndim
和reps的长度d
中最大的一个,即max(d,A.ndim)
如果A.ndim<d
,数组A会被升维到d维,通过在其前面增加new axes。如(3,)可以被升维到二维(1,3),三维(1,1,3)。如果不希望这样的行为,那么需要在调用tile前手动升维。
如果A.ndim>d
,reps会通过前置1的方式被“升维”到A.ndim,如A.shape为(2,3,4,5),给定的reps为(2,2)。那么reps会被当做(1,1,2,2)处理。
参数与返回值
Parameters
- A : array_like
The input array.- reps : array_like
The number of repetitions ofA
along each axis.
- A: array_like
输入数组A - reps: array_like
每一维度A的重复次数
Returns
- c : ndarray
The tiled output array.
- c : ndarray
输出数组
Example
仔细观察下面的例子,你会发现:
- 首先,返回数组的shape十分有规律,就是升维后的shape与reps的相乘。
- 其次,返回数组十分有规律。就像贴瓷砖一样,将原数组当做瓷砖,一块一块的进行贴合。(搭积木一般)
>>> a = np.array([0, 1, 2])
# a.ndim == len(reps)
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
# a.ndim < len(reps), a被升维为(1,3),返回结果为(2,6)
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
# a.ndim < len(reps), a被升维为(1,1,3),返回结果为(2,1,6)
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
[[0, 1, 2, 0, 1, 2]]])
>>> b = np.array([[1, 2], [3, 4]])
# b.ndim > len(reps),reps被作为(1,2)处理,返回结果为(2,4)
>>> np.tile(b, 2)
array([[1, 2, 1, 2],
[3, 4, 3, 4]])
# b.ndim == len(reps), 返回结果为(4,2)
>>> np.tile(b, (2, 1))
array([[1, 2],
[3, 4],
[1, 2],
[3, 4]])
# c.ndim < len(reps),c被升维为(1,4),返回结果为(4,4)
>>> c = np.array([1,2,3,4])
>>> np.tile(c,(4,1))
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
类似的函数
repeat : Repeat elements of an array.
broadcast_to : Broadcast an array to a new shape