交错numpy数组 [英] Interleave numpy arrays
本文介绍了交错numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试按以下方式插入数组.
I'm trying to interleave arrays as below.
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]]
是否有一种优雅的方法?
Is there an elegant way to do this?
这是我的写作方式,但我一直在寻求改进. data=np.array([x,y[0],x,y[1],x,y[2]])
还有其他写方法吗?
This is my the way I wrote, but I was looking to improve this line. data=np.array([x,y[0],x,y[1],x,y[2]])
Any other way to write this?
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)
推荐答案
您可以尝试使用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
中您要在插入之前插入的索引.
(0, 1, 2)
refers to the indexes in y
that you would like to insert into before insertion.
编辑:可以将obj=range(y.shape[0])
用于y
的任意长度.感谢Chiel的建议.
EDIT : One can use obj=range(y.shape[0])
for arbitrary length of y
. Thanks for Chiel's suggestion.
有关更多信息,请参见 tutorial
.
Please see the tutorial
for more information.
这篇关于交错numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文