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