gpt4 book ai didi

python - 重复二维数组的行

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:18 26 4
gpt4 key购买 nike

我有一个 numpy 数组,我想在保留行的原始顺序的同时重复它 n 次:

>>>a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

期望的输出(对于 n =2):

>>>a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

我找到了一个 np.repeat 函数,但是它没有保留列的原始顺序。是否有任何其他内置函数或技巧可以在保留顺序的同时重复数组?

最佳答案

这是另一种方法。我还添加了一些与@coldspeed 解决方案的时间比较

n = 2
a_new = np.tile(a.flatten(), n)
a_new.reshape((n*a.shape[0], a.shape[1]))
# array([[ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11],
# [ 0, 1, 2, 3],
# [ 4, 5, 6, 7],
# [ 8, 9, 10, 11]])

与coldspeed解决方案的性能比较

我的方法 n = 10000

a = np.array([[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
n = 10000

def tile_flatten(a, n):
a_new = np.tile(a.flatten(), n).reshape((n*a.shape[0], a.shape[1]))
return a_new

%timeit tile_flatten(a,n)
# 149 µs ± 20.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

coldspeed 的解决方案 1 对于 n = 10000

a = np.array([[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
n = 10000

def concatenate_repeat(a, n):
a_new = np.concatenate(np.repeat(a[None, :], n, axis=0), axis=0)
return a_new

%timeit concatenate_repeat(a,n)
# 7.61 ms ± 1.37 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

coldspeed 的解决方案 2 对于 n = 10000

a = np.array([[ 0,  1,  2,  3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
n = 10000

def broadcast_reshape(a, n):
a_new = np.broadcast_to(a, (n, *a.shape)).reshape(-1, a.shape[1])
return a_new

%timeit broadcast_reshape(a,n)
# 162 µs ± 29.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

@user2357112的解决方案

def tile_only(a, n):
a_new = np.tile(a, (n, 1))
return a_new

%timeit tile_only(a,n)
# 142 µs ± 21.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

关于python - 重复二维数组的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com