gpt4 book ai didi

python - 快速重复(垂直)二维数组的每一半的numpy方法

转载 作者:行者123 更新时间:2023-11-30 22:28:33 26 4
gpt4 key购买 nike

假设我们有以下二维数组:

In [200]: a = np.arange(8).reshape(4,2)

In [201]: a
Out[201]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])

如何重复它的每一半,所以我有以下二维数组:

array([[0, 1],
[2, 3],
[0, 1],
[2, 3],
[4, 5], # second half
[6, 7],
[4, 5],
[6, 7]])

我的尝试产生了错误的结果:

In [202]: np.tile(np.split(a, 2), 2).reshape(-1,2)
Out[202]:
array([[0, 1],
[0, 1],
[2, 3],
[2, 3],
[4, 5],
[4, 5],
[6, 7],
[6, 7]])

最佳答案

reshape 将第一个轴分成两个,给我们一个 3D 数组,然后沿着第一个轴重复,最后 reshape 回 2D -

np.repeat(a.reshape(-1,2,2),2,axis=0).reshape(-1,2)

概括它 -

def repeat_blocks(a):
N = a.shape[0]
B = N//2 # Block length
R = 2 # number of repeats
out = np.repeat(a.reshape(N//B,B,-1),R,axis=0).reshape(N*R,-1)
return out

示例运行 -

案例#1:

In [120]: a
Out[120]:
array([[0, 1],
[2, 3],
[4, 5],
[6, 7]])

In [121]: repeat_blocks(a)
Out[121]:
array([[0, 1],
[2, 3],
[0, 1],
[2, 3],
[4, 5],
[6, 7],
[4, 5],
[6, 7]])

案例#2:

In [123]: a
Out[123]:
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11]])

In [124]: repeat_blocks(a)
Out[124]:
array([[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9],
[10, 11],
[ 6, 7],
[ 8, 9],
[10, 11]])

关于python - 快速重复(垂直)二维数组的每一半的numpy方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594536/

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