2

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:

  • both axes of Array A will always have the same size eg 200x200 up to 4096x4096
  • Array B axes sizes may differ eg. 50x60, but ArrayB will always fit into Array A, in other words array B will never overlap Array A.
1
  • @zhangxaochen - thnx for the arrays formatting:) Commented Feb 25, 2014 at 12:45

2 Answers 2

2
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]]
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

this works only for the exact example I mentioned above, if I change bigger array(4x4) to let's 5x5 or even bigger or change the position to eg 0 0 I get an error: 'ValueError: could not broadcast input array from shape (3,3) into shape (4,4)'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.