numpy.tile作用,语法,参数分析以及举例

14 篇文章 2 订阅

numpy.tile

语法

numpy.tile(A,reps)

作用

Construct an array by repeating A the number of times given by reps.

If reps has length d, 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, promote A to d-dimensions manually before calling this
function.

If A.ndim > d, reps is promoted to A.ndim by pre-pending 1’s to it.
Thus for an A of shape (2, 3, 4, 5), a reps 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 of A 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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值