NumPy repeat()

repeat() 方法将输入数组的元素重复给定次数。

示例

import numpy as np

numbers = np.array([0, 1, 2, 3])

# repeat each element twice repeatedArray = np.repeat(numbers, 2)
print(repeatedArray) # Output : [0 0 1 1 2 2 3 3]

repeat() 语法

repeat() 的语法是

numpy.repeat(array, repetitions, axis)

repeat() 参数

repeat() 方法接受三个参数

  • array - 一个包含要重复的元素的数组
  • repetitions - 元素重复的次数
  • axis (可选) - 沿哪个轴重复数组的元素

repeat() 返回值

repeat() 方法返回带有重复元素的数组。


示例 1: numpy.repeat()

import numpy as np

# create a 2D array
array1 = np.array([[0, 1], [2, 3]])

# set the number of times each element should repeat
repetitions = 3

# repeat each element thrice repeatedArray = np.repeat(array1, repetitions)
print(repeatedArray)

输出

[0 0 0 1 1 1 2 2 2 3 3 3]

这里,二维数组 array1 首先被展平,然后其每个元素重复三次。


示例 2: 带轴的 numpy.repeat()

对于多维数组,我们可以使用 axis 参数来指定重复应该发生的轴。

当轴为 0 时,数组的行垂直重复。当轴为 1 时,列水平重复。

让我们看一个例子。

import numpy as np

array1 = np.array([[0, 1], [2, 3]])

repetitions = 2

# repeat the elements along axis 0 repeatedArray = np.repeat(array1, repetitions, 0)
print('Along axis 0\n', repeatedArray)
# repeat the elements along axis 1 repeatedArray = np.repeat(array1, repetitions, 1)
print('Along axis 1\n', repeatedArray)

输出

Along axis 0
[[0 1]
 [0 1]
 [2 3]
 [2 3]]
Along axis 1
 [[0 0 1 1]
 [2 2 3 3]]

示例 3: 不均匀的重复

到目前为止的示例是将数组的每个元素重复固定次数。

但是,我们可以按不同的数量重复不同的元素。

import numpy as np

array1 = np.array([[0, 1, 2, 3]])

# set different repetition counts for each array element repetitions = [2, 3, 1, 2] # uneven repetition of the elements repeatedArray = np.repeat(array1, repetitions)
print(repeatedArray)

输出

[0 0 1 1 1 2 3 3]

这里,第一个元素(0)重复 2 次,第二个元素(1)重复 3 次,依此类推。


示例 4: 使用 Repeat 创建数组

我们也可以使用 repeat() 创建数组。

import numpy as np

# create an array of four 3s 
repeatedArray = np.repeat(3, 4)

print(repeatedArray)

输出

[3 3 3 3]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战