tile()
方法通过重复数组来构造一个新数组。
示例
import numpy as np
# create an array
array1 = np.array([0, 1, 2, 3, 4])
# create an array by repeating array1 3 times
array2 = np.tile(array1, 3)
print(array2)
# Output: [0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]
tile() 语法
tile()
的语法是
numpy.tile(array, repetitions)
tile() 参数
tile()
方法接受两个参数:
array
- 要重复的数组元素repetitions
- 数组重复的次数
tile() 返回值
tile()
方法返回一个包含输入数组重复的新数组。
示例 1:平铺一维数组
import numpy as np
# create an array
array1 = np.array([0, 1])
# tile array1 3 times
array2 = np.tile(array1, 3)
# tile array1 2 times in axis-0 and 3 times in axis-1
array3 = np.tile(array1, (2, 3))
print('1-D tile:\n', array2)
print('2-D tile:\n', array3)
输出
1-D tile: [0 1 0 1 0 1] 2-D tile: [[0 1 0 1 0 1] [0 1 0 1 0 1]]
在下面的代码片段中,
array3 = np.tile(array1,(2, 3))
元组 (2, 3) 表示 array1 沿轴 0 重复 2 次,沿轴 1 重复 3 次。这将产生一个二维数组,其中包含重复的模式。
注意:np.tile(array1, 0)
会移除数组中的所有元素。
示例 2:平铺二维数组
我们可以像平铺一维数组一样平铺二维数组。
import numpy as np
# create an array
array1 = np.array(
[[0, 1, 2],
[3, 4, 5]])
# tile twice
array2 = np.tile(array1, 2)
# tile twice on axis-0 and thrice on axis-1
array3 = np.tile(array1, (2,3))
# tile twice in each axis to make a 3-D array
array4 = np.tile(array1, (2, 2, 2))
print('\nTile with 2 repetitions:\n',array2)
print('\nTile with (2,3) repetitions:\n',array3)
print('\nTile to make a 3-D array:\n',array4)
输出
Tile with 2 repetitions: [[0 1 2 0 1 2] [3 4 5 3 4 5]] Tile with (2,3) repetitions: [[0 1 2 0 1 2 0 1 2] [3 4 5 3 4 5 3 4 5] [0 1 2 0 1 2 0 1 2] [3 4 5 3 4 5 3 4 5]] Tile to make a 3-D array: [[[0 1 2 0 1 2] [3 4 5 3 4 5] [0 1 2 0 1 2] [3 4 5 3 4 5]] [[0 1 2 0 1 2] [3 4 5 3 4 5] [0 1 2 0 1 2] [3 4 5 3 4 5]]]
注意:np.tile()
类似于 np.repeat()
,主要区别在于 tile()
重复的是数组,而 repeat()
重复的是数组的单个元素。