python – 在2D numpy数组中对角插入元素的最快方法是什么?

假设我们有一个2D numpy数组,如:

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          [10, 11, 12]]

我想在对角线插入一个值0,使其变为:

matrix = [[0, 1, 2, 3],
          [4, 0, 5, 6],
          [7, 8, 0, 9],
          [10, 11, 12, 0]]

最快的方法是什么?

解决方法:

创建一个新的更大的矩阵,剩下的空间为零.将原始矩阵复制到子矩阵,剪辑和重塑:

matrix = numpy.array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          [10, 11, 12]])

matrix_new = numpy.zeros((4,5))
matrix_new[:-1,1:] = matrix.reshape(3,4)
matrix_new = matrix_new.reshape(-1)[:-4].reshape(4,4)

或者以更一般化的形式:

matrix = numpy.array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9],
          [10, 11, 12]])

d = matrix.shape[0]
assert matrix.shape[1] == d - 1
matrix_new = numpy.ndarray((d, d+1), dtype=matrix.dtype)
matrix_new[:,0] = 0
matrix_new[:-1,1:] = matrix.reshape((d-1, d))
matrix_new = matrix_new.reshape(-1)[:-d].reshape(d,d)
上一篇:python – NumPy – 2D矩阵二次诊断元素的总和


下一篇:【LeetCode】4.Array and String — Diagonal Traverse 对角线遍历