dreamak
dreamak

Reputation: 23

Merge 2d arrays(different dimensions) at specified row/column in python

Is there a way to combine two 2d arrays(preferably numpy arrays) of different dimensions starting at specified position, e.g. merge 3x3 into 4x4 array starting at position 1 1:

Array A

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4

Array B

5 5 5
5 5 5
5 5 5

resulting array

1 1 1 1
2 5 5 5
3 5 5 5
4 5 5 5

some more notes:

Upvotes: 2

Views: 368

Answers (2)

zhangxaochen
zhangxaochen

Reputation: 34047

In [231]: def merge(a, b, pos):
     ...:     res=a[:]
     ...:     res[pos[0]:pos[0]+b.shape[0], pos[1]:pos[1]+b.shape[1]]=b
     ...:     return res

In [232]: C=merge(A, B, (1,1))
     ...: print C
[[1 1 1 1]
 [2 5 5 5]
 [3 5 5 5]
 [4 5 5 5]]

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

In [32]: a2 = np.loadtxt(StringIO.StringIO("""5 5 5\n 5 5 5\n 5 5 5"""))                         

In [33]: a1 = np.loadtxt(StringIO.StringIO("""1 1 1 1\n 2 2 2 2\n 3 3 3 3\n 4 4 4 4"""))         

In [34]: a1[1:, 1:] = a2                                                                         

In [35]: a1
Out[35]: 
array([[ 1.,  1.,  1.,  1.],                                                                     
       [ 2.,  5.,  5.,  5.],                                                                     
       [ 3.,  5.,  5.,  5.],                                                                     
       [ 4.,  5.,  5.,  5.]])   

Upvotes: 2

Related Questions