How to combine two 2D array into the following in Python?

假装没事ソ 提交于 2020-01-16 11:59:08

问题


Suppose I have 2 2D array as follows:

A = [[1, 2],
     [3, 4]]

B = [[5, 6, 7],
     [8, 9, 8],
     [7, 6, 5]]

Is there a numpy function to combine A and B into C as follows?

C = [[1, 2, 0, 0, 0],
     [3, 4, 0, 0, 0],
     [0, 0, 5, 6, 7],
     [0, 0, 8, 9, 8],
     [0, 0, 7, 6, 5]]

Thanks


回答1:


If you expect to be making many linear algebraic operations, NumPy/SciPy will be your friend. For the particular problem of creating block diagonal matrices, scipy.linalg.block_diag saves the day:

In [14]: from scipy.linalg import block_diag

In [16]: A = [[1, 2],
    ...:      [3, 4]]
    ...:

In [17]: B = [[5, 6, 7],
    ...:      [8, 9, 60],
    ...:      [10, 20, 0]]
    ...:

In [18]: block_diag(A, B)
Out[18]:
array([[ 1,  2,  0,  0,  0],
       [ 3,  4,  0,  0,  0],
       [ 0,  0,  5,  6,  7],
       [ 0,  0,  8,  9, 60],
       [ 0,  0, 10, 20,  0]], dtype=int32)

Otherwise (edit: noting that the question in its original form did not actually specify that the desired solution involved NumPy), if you just want to do it with vanilla Python, assuming that all blocks are square you could do something like

[a + [0]*len(B) for a in A] + [[0]*len(A) + b for b in B]



回答2:


You can develop your own program to do that, shouldn't be too difficult.

Here are some starting steps:

  1. Front append 0's in all elemnts of A and back append 0's in all elements of B to make their lengths equal.

  2. Then simply fill in the values of A and B in the resulting matrix.



来源:https://stackoverflow.com/questions/50659491/how-to-combine-two-2d-array-into-the-following-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!