Python: Numpy的tile函数

tile函数

根据numpy官方的说明1,tile函数的作用为:

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.

简而言之,tile函数的作用就是将数组A以reps作为次数进行扩充。reps同样可以为矩阵。最总生成的数组的维度为A和reps二者维度的最大值。
另外,由于tile函数所生成的为numpy中的array结构,而array与python自带list等类型不同,array中的元素必须属于同样的数据类型。如果不同类型则会进行强制转换。

tile函数应用举例

1 一维扩充实例

// An highlighted block
from numpy import tile
a = [0,1,2]
b = tile(a,3)
b

输出的结果是:

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

可以看到,结果是把一维向量[0,1,2]扩充为一维向量[0,1,2,0,1,2,0,1,2]。

2 矩阵扩充实例

reps为矩阵的实例:

// An highlighted block
from numpy import tile
a = [['A','B'],['C','D']]
b = tile(a,(2,3))
b

输出的结果是:

array([['A', 'B', 'A', 'B', 'A', 'B'],
       ['C', 'D', 'C', 'D', 'C', 'D'],
       ['A', 'B', 'A', 'B', 'A', 'B'],
       ['C', 'D', 'C', 'D', 'C', 'D']], dtype='<U1')

可以看到,结果是把大小为(2,2)的二维矩阵a扩充为大小为(4,6)的二维矩阵b。对应到函数语法中,即reps[0]扩充了A矩阵的行数大小,reps[1]扩充了A矩阵的列数大小。

3 补充说明

如果用于产生数组的变量A为元素属于不同类型的列表list或元组tuple,会进行强制类型转换。

// An highlighted block
from numpy import tile
a = [0,'a']
b = tile(a,3)
b

输出的结果则是:

array(['1', 'a', '1', 'a', '1', 'a'], dtype='<U11')

  1. https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html#numpy.tile ↩︎

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值