np.repeat()

np.repeat()

np.repeat(a, repeats, axis=None)

输入: a是数组,repeats是各个元素重复的次数(repeats一般是个标量,稍复杂点是个list),在axis的方向上进行重复

返回: 如果不指定axis,则将重复后的结果展平(维度为1)后返回;如果指定axis,则不展平

1
import numpy as np

1
2
3
# 示例1,展平
# 将3重复4次
np.repeat(a=3, repeats=4)
1
array([3, 3, 3, 3])
1
2
3
4
# 示例2,展平
# 每个元素都重复2次,并展平后输出
x = np.array([[1,2],[3,4]])
np.repeat(a=x, repeats=2)
1
array([1, 1, 2, 2, 3, 3, 4, 4])

1
2
3
4
#示例3,不展平
x = np.array([[1,2],[3,4]])
# 沿着axis=1方向重复,将axis=1方向上的每个元素重复3次
np.repeat(a=x, repeats=3, axis=1)
1
2
array([[1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4]])
1
2
3
4
5
#示例3,不展平
x = np.array([[1,2],[3,4]])
# 沿着axis=0方向重复,将axis=0方向上的第0个元素重复1次,第1个元素重复2次
np.repeat(a=x, repeats=[1, 2], axis=0)
# array([[1, 2], [3, 4], [3, 4]])
1
2
3
array([[1, 2],
       [3, 4],
       [3, 4]])