此问题已在此处有答案:
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)
2条答案
按热度按时间ehxuflar1#
可以使用
np.insert
(0, 1, 2)
引用了y
中的索引,您希望在插入之前将其插入。可以使用
obj=range(y.shape[0])
来表示任意长度的y
。请参阅
tutorial
了解更多信息。zour9fqk2#
根据答案https://stackoverflow.com/a/5347492/7505395改编为Interweaving two numpy arrays:
输出: