如何将一个ndarray插入到另一个ndarray? [英] How to insert one ndarray to another ndarray?
本文介绍了如何将一个ndarray插入到另一个ndarray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是两个ndarray.
These are two ndarray.
A=[[1,2,3],[4,5,6],[7,8,9]]
B=[[31,42,53],[11,17,29],[100,59,32]]
如何通过合并两个ndarray A和B来制作新的ndarray'C'?
How to make a new ndarray 'C' by merge two ndarray A and B?
C=[[1,2,3],[31,42,53],[4,5,6], [11,17,29],[7,8,9],[100,59,32]]
推荐答案
使用array-initialization
完成该交织任务-
def interweave(a, b):
N = a.shape[1]
M = a.shape[0] + b.shape[0]
out_dtype = np.result_type(a.dtype, b.dtype)
out = np.empty((M,N),dtype=out_dtype)
out[::2] = a
out[1::2] = b
return out
样品运行-
In [274]: A
Out[274]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [275]: B
Out[275]:
array([[ 31, 42, 53],
[ 11, 17, 29],
[100, 59, 32]])
In [276]: interweave(A, B)
Out[276]:
array([[ 1, 2, 3],
[ 31, 42, 53],
[ 4, 5, 6],
[ 11, 17, 29],
[ 7, 8, 9],
[100, 59, 32]])
如果A
和B
具有相同的形状,我们还可以堆叠和重塑-
If A
and B
are of same shapes, we can also stack and reshape -
In [283]: np.hstack((A,B)).reshape(-1,A.shape[1])
Out[283]:
array([[ 1, 2, 3],
[ 31, 42, 53],
[ 4, 5, 6],
[ 11, 17, 29],
[ 7, 8, 9],
[100, 59, 32]])
或np.stack((A,B),axis=1).reshape(-1,A.shape[1])
.
这篇关于如何将一个ndarray插入到另一个ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文