交错numpy数组

时间:2018-01-28 15:24:37

标签: python numpy

我试图按如下方式交错数组。

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9])

期望的结果:

[[1,2,3,4,5],[4,6,2,6,9],[1,2,3,4,5],[5,9,8,7,4],[1,2,3,4,5],[3,2,5,4,9]]

有优雅的方法吗?

这是我写作的方式,但我希望改进这一行。 data=np.array([x,y[0],x,y[1],x,y[2]])还有其他任何方法可以写这个吗?

x=np.array([1,2,3,4,5])     
y=np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]]) 

data=np.array([x,y[0],x,y[1],x,y[2]])
print(data)

2 个答案:

答案 0 :(得分:3)

您可以尝试使用np.insert

import numpy as np

x = np.array([1,2,3,4,5])
y = np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]])
np.insert(y, obj=(0, 1, 2), values=x, axis=0)

array([[1, 2, 3, 4, 5],
       [4, 6, 2, 6, 9],
       [1, 2, 3, 4, 5],
       [5, 9, 8, 7, 4],
       [1, 2, 3, 4, 5],
       [3, 2, 5, 4, 9]])

(0, 1, 2)是指在插入之前要插入的y中的索引。

编辑:可以obj=range(y.shape[0])使用y的任意长度。感谢Chiel的建议。

有关详细信息,请参阅tutorial

答案 1 :(得分:0)

改编自答案https://stackoverflow.com/a/5347492/7505395Interweaving two numpy arrays

import numpy as np
x=np.array([1,2,3,4,5])     
y=np.array([[4,6,2,6,9],[5,9,8,7,4],[3,2,5,4,9]]) # fixed missing []

x_enh = np.array([x]*len(y)) # blow up x to y size 

c = np.empty((y.size * 2,), dtype=y.dtype).reshape(y.size,5) # create correctly sized empty
c[0::2] = x_enh   # interleave using 2 steps starting on 0
c[1::2] = y       # interleave using 2 steps starting on 1

print(c)

输出:

[[1 2 3 4 5]
 [4 6 2 6 9]
 [1 2 3 4 5]
 [5 9 8 7 4]
 [1 2 3 4 5]
 [3 2 5 4 9]]