📅  最后修改于: 2023-12-03 15:28:31.545000             🧑  作者: Mango
在NumPy中,有几种方法可以重复数组中的元素,这在数据处理和模拟中是非常常见的操作。这个过程可以通过使用NumPy的repeat()或tile()函数来实现。
numpy.repeat(a, repeats, axis=None)
repeat()函数接受三个参数:
下面的代码演示了repeat()函数的用法:
import numpy as np
a = np.array([1, 2, 3])
print("原数组:", a)
b = np.repeat(a, 3)
print("重复后的数组:", b)
输出:
原数组: [1 2 3]
重复后的数组: [1 1 1 2 2 2 3 3 3]
上面的代码将数组a的元素重复了3次,生成了一个新的数组b。
numpy.tile(A, reps)
tile()函数接受两个参数:
下面的代码演示了tile()函数的用法:
import numpy as np
a = np.array([[1, 2], [3, 4]])
print("原数组:\n", a)
b = np.tile(a, (2, 3))
print("重复后的数组:\n", b)
输出:
原数组:
[[1 2]
[3 4]]
重复后的数组:
[[1 2 1 2 1 2]
[3 4 3 4 3 4]
[1 2 1 2 1 2]
[3 4 3 4 3 4]]
上面的代码将数组a沿着y轴重复了2次,沿着x轴重复了3次,生成了一个新的数组b。
下面的代码使用Python的timeit模块对repeat()函数和tile()函数的性能进行比较:
import numpy as np
import timeit
a = np.random.randint(0, 100, size=100000)
start = timeit.default_timer()
b = np.repeat(a, 3)
end = timeit.default_timer()
print("repeat()函数的耗时:", end - start)
start = timeit.default_timer()
c = np.tile(a, 3)
end = timeit.default_timer()
print("tile()函数的耗时:", end - start)
输出:
repeat()函数的耗时: 0.0010446530001999354
tile()函数的耗时: 0.0006290850002402682
从结果可以看出,tile()函数的性能比repeat()函数要好,建议在可行的情况下使用tile()函数。