问题
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:
Front append 0's in all elemnts of A and back append 0's in all elements of B to make their lengths equal.
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