ermutuxia

2022-03-02   阅读量: 1132

Python

np.tile函数的用法

扫码加入数据分析学习群

In [7]: help(tile)

Help on function tile in module numpy:


tile(A, reps)

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

通过对A按照指定要求重复若干次来构建一个数组。这个指定要求通过reps参数来设定。


If `reps` has length ``d``, the result will have dimension of

``max(d, A.ndim)``.

如果reps参数的长度为d,则返回的数组的维数是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.

如果A的维数小于d,则返回的数组的维数是d,通过给A追加新的轴来实现。

所以一个shape为(3,)的一维数组,可以晋级为shape为(1,3)二维数组,也可以晋级为shape为(1,1,3)的三维数组。




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

如果A的维数大于d,则reps长度会被晋级为A的维数。对于reps长度不足的地方会被预填为1。

所以对于一个shape为(2,3,4,5)的四维数组A,如果reps参数被设定为了(2,2),则reps会被当成(1,1,2,2)对待。



Note : Although tile may be used for broadcasting, it is strongly

recommended to use numpy's broadcasting operations and functions.

备注:尽管tile函数可以被用于广播,但是我们还是强烈建议您使用numpy的广播运算和函数。

Parameters 参数介绍

----------

A : array_like 一个类数组

The input array.

reps : array_like 一个类数组

The number of repetitions of `A` along each axis.指定在某一个轴上重复的长度。


Returns

-------

c : ndarray

The tiled output array. 返回一个数组。


See Also 也可以看下repeat和broadcast_to这两个函数。

--------

repeat : Repeat elements of an array.

broadcast_to : Broadcast an array to a new shape


Examples

--------

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

>>> np.tile(a, 2) 在0轴上重复为原来的二倍

array([0, 1, 2, 0, 1, 2])

>>> np.tile(a, (2, 2)) 在0轴上重复为原来的二倍,在1轴上重复为原来的二倍

array([[0, 1, 2, 0, 1, 2],

[0, 1, 2, 0, 1, 2]])

>>> np.tile(a, (2, 1, 2)) 在0轴上重复为原来的二倍,在1轴上重复为原来的一倍,在2轴上重复为原来的二倍

array([[[0, 1, 2, 0, 1, 2]],

[[0, 1, 2, 0, 1, 2]]])


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

>>> np.tile(b, 2) 在0轴上不变,在1轴上重复为原来的二倍

array([[1, 2, 1, 2],

[3, 4, 3, 4]])

>>> np.tile(b, (2, 1))

array([[1, 2],

[3, 4],

[1, 2],

[3, 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]])



下面这个例子可能讲的更明白一些

In [8]: tile([1,2],(3,1) )

Out[8]:

array([[1, 2],

[1, 2],

[1, 2]])

从内向外不断扩展,然后原来的A是一维,reps长度为2,那就先需要在原来A的最外面加一层中括号,使其变为二维。然后在0轴上的轴长变为原来的三倍,在1轴上的轴长是原来的一倍。

添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
110.2671 5 0 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子