交错NumPy数组[重复]

sf6xfgos  于 2023-04-21  发布在  其他
关注(0)|答案(2)|浏览(98)

此问题已在此处有答案

Interweaving two NumPy arrays efficiently(13个回答)
4年前关闭。
我正在尝试交错数组如下。

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

ehxuflar1#

可以使用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
请参阅tutorial了解更多信息。

zour9fqk

zour9fqk2#

根据答案https://stackoverflow.com/a/5347492/7505395改编为Interweaving 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]]

相关问题