Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

python - How to insert one ndarray to another 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]]

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]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using array-initialization to achieve that interweaving task -

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

Sample run -

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

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

Or np.stack((A,B),axis=1).reshape(-1,A.shape[1]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...