简体   繁体   English

在Python中的指定行/列上合并二维数组(不同维度)

[英]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, eg merge 3x3 into 4x4 array starting at position 1 1: 有没有一种方法可以从指定位置开始合并两个不同尺寸的2d数组(最好是numpy数组),例如,将3x3合并为从位置1开始的4x4数组1:

Array A 阵列A

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

Array B 阵列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 阵列A的两个轴将始终具有相同的大小,例如200x200至4096x4096
  • Array B axes sizes may differ eg. 阵列B轴的尺寸可能不同,例如。 50x60, but ArrayB will always fit into Array A, in other words array B will never overlap Array A. 50x60,但ArrayB将始终适合于Array A,换句话说,Array B永远不会与Array A重叠。
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.]])   
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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM