Python 如何对两个numpy数组的每n行进行堆栈

Python 如何对两个numpy数组的每n行进行堆栈,python,numpy,Python,Numpy,我有2个numpy阵列,我希望按如下方式堆叠它们: arr1 = [[1,2,3] [4,5,6] [7,8,9] [10,11,12]] arr2 = [[a,b,c] [d,e,f] [g,h,i] [j,k,l]] SomeStackFunction(a,b) # need this funtion output

我有2个numpy阵列,我希望按如下方式堆叠它们:

    arr1 = [[1,2,3]
            [4,5,6]
            [7,8,9]
            [10,11,12]]
    arr2 = [[a,b,c]
            [d,e,f]
            [g,h,i]
            [j,k,l]]

    SomeStackFunction(a,b) # need this funtion

    output_array = [[1,2,3]
                    [4,5,6]
                    [a,b,c]
                    [d,e,f]
                    [7,8,9]
                    [10,11,12]
                    [g,h,i]
                    [j,k,l]]

最有效的方法是什么?我有相当大的数组,实际上希望每4行堆栈一次。

如果有numpy数组,可以使用中描述的numpy stack函数

文档中的示例:

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])
np.stack((a, b))
--> array([[1, 2, 3],
           [2, 3, 4]])
您可以尝试以下方法:

arr1 = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [10, 11, 12]]

arr2 = [['a', 'b', 'c'],
        ['d', 'e', 'f'],
        ['g', 'h', 'i'],
        ['j', 'k', 'l']]

[e for tup in list(zip(arr1[::2], arr1[1::2], arr2[::2], arr2[1::2])) for e in tup]

# Out[67]: 
# [[1, 2, 3],
#  [4, 5, 6],
#  ['a', 'b', 'c'],
#  ['d', 'e', 'f'],
#  [7, 8, 9],
#  [10, 11, 12],
#  ['g', 'h', 'i'],
#  ['j', 'k', 'l']]

如果出于某种原因您不想使用numpy:

arr1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
arr2 = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l']]

output_array = []
ind1 = 0
ind2 = 0

for i in range(len(arr1)):

    if i % 2 == 0:
        output_array.append(arr1[ind1])
        ind1 += 1
        output_array.append(arr1[ind1])
        ind1 += 1
    else:
        output_array.append(arr2[ind2])
        ind2 += 1
        output_array.append(arr2[ind2])
        ind2 += 1
输出:

[[1, 2, 3],[4, 5, 6],['a', 'b', 'c'],['d', 'e', 'f'],[7, 8, 9],[10, 11, 12],['g', 'h', 'i'],['j', 'k', 'l']]
>>> print(out)
[[  0   1   2]
 [  3   4   5]
 [  0  10  20]
 [ 30  40  50]
 [  6   7   8]
 [  9  10  11]
 [ 60  70  80]
 [ 90 100 110]]

如果你能用numpy,我有一个有趣的:

arr1 = np.asarray([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
arr2 = np.asarray([[0,10,20],[30,40,50],[60,70,80],[90,100,110]])

tmp_arr1  = arr1.reshape((arr1.shape[0]//2, -1))
tmp_arr2 = arr2.reshape((arr2.shape[0]//2, -1))

out = np.stack((tmp_arr1, tmp_arr2), axis=1).reshape((2*arr1.shape[0],arr1.shape[1]))
输出:

[[1, 2, 3],[4, 5, 6],['a', 'b', 'c'],['d', 'e', 'f'],[7, 8, 9],[10, 11, 12],['g', 'h', 'i'],['j', 'k', 'l']]
>>> print(out)
[[  0   1   2]
 [  3   4   5]
 [  0  10  20]
 [ 30  40  50]
 [  6   7   8]
 [  9  10  11]
 [ 60  70  80]
 [ 90 100 110]]

这种方法可能看起来相当混乱,但只使用numpy函数可以提供非常好的性能。对于你的问题来说,这可能有点过头了,但知道这可以通过一点独创性来解决还是不错的。

这只是问题的一半。OP想要交错2个数组。总是2行a和2行b.TBH,我不知道为什么会这样。tmp_arr阵列看起来像一堆杂乱无章的疯子。但它完全符合我的需要。只是将//2改为//4,以每4行替换一次,而不是每2行。这里绝对有些独创性。但它能快速有效地满足我的需求。非常感谢。