How To Combine Two 2d Array Into The Following In Python?
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
Solution 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]
Post a Comment for "How To Combine Two 2d Array Into The Following In Python?"