本文介绍了快速的numpy方式(垂直)重复二维数组的每一半的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假定我们具有以下2D数组:

Assuming we have the following 2D array:

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

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

如何重复其中的每一半,所以我有以下2D数组:

How may repeat each half of it, so I have the following 2D array:

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

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

My attempt produces wrong result:

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]])


推荐答案

将第一个轴拆分为两个给我们3D阵列,然后沿冷杉重复t,最后重塑为2D-

Reshape to split the first axis into two giving us a 3D array, then repeat along the first and finally reshape back to 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]])

这篇关于快速的numpy方式(垂直)重复二维数组的每一半的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:27