获取高阵列的对角线索引

问题描述 投票:0回答:2

我的阵列大小为5 x 3 x 3。 我想用一个数字填充每个3 x 3块的对角线。 如何使用numpy(一个python库)有效地做到这一点。

我的起始矩阵是这样的:

[[[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]

 [[0 0 0]
  [0 0 0]
  [0 0 0]]]

我想要这样的东西:

[[[0.07735655 0         0        ]
  [0         0.11476396 0        ]
  [0         0         0.09903619]]

 [[0.1923885  0         0        ]
  [0         0.03063454 0        ]
  [0         0         0.06028193]]

 [[0.06566275 0         0        ]
  [0         0.03151423 0        ]
  [0         0         0.04042383]]

 [[0.07950743 0         0        ]
  [0         0.03250461 0        ]
  [0         0         0.0448308 ]]

 [[0.10879917 0         0        ]
  [0         0.04700161 0        ]
  [0         0         0.03924387]]]
python numpy multidimensional-array numpy-ndarray diagonal
2个回答
1
投票

你可以用这个:

diag_ind_y, diag_ind_x = np.diag_indices(3)
arr1[:, diag_ind_y, diag_ind_x] = diag_vals

测试出来:

import numpy as np

arr1 = np.zeros(shape=(5,3,3), dtype=np.float64)   # Your array
diag_vals = np.random.rand(5,3)                    # The source of your diag values
diag_ind_y, diag_ind_x = np.diag_indices(3)        # Returns arrays [0,1,2] and [0,1,2]
arr1[:, diag_ind_y, diag_ind_x] = diag_vals
print (arr1)

输出:

[[[0.69514006 0.         0.        ]
  [0.         0.4014048  0.        ]
  [0.         0.         0.473671  ]]

 [[0.12769874 0.         0.        ]
  [0.         0.8565723  0.        ]
  [0.         0.         0.69453857]]

 [[0.00943213 0.         0.        ]
  [0.         0.81497541 0.        ]
  [0.         0.         0.6915095 ]]

 [[0.33894452 0.         0.        ]
  [0.         0.24649647 0.        ]
  [0.         0.         0.61987433]]

 [[0.30184036 0.         0.        ]
  [0.         0.66978532 0.        ]
  [0.         0.         0.34574364]]]

1
投票

使用for循环和numpy.fill_diagonal怎么样?

In [33]: zeros = np.zeros((5, 3, 3))

# desired values to be filled along the diagonals; 
# can also be 1D numpy arrays instead of Python lists
In [34]: diagonals = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

In [35]: for idx, diag in enumerate(diagonals):
    ...:     np.fill_diagonal(zeros[idx], diag)
    ...:     

In [36]: zeros
Out[36]: 
array([[[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]]])
© www.soinside.com 2019 - 2024. All rights reserved.