gpt4 book ai didi

python-3.x - 如何获取 numpy 3-D 数组的对角线分量?

转载 作者:行者123 更新时间:2023-12-02 20:33:02 25 4
gpt4 key购买 nike

我有一个像这样的 3-D 数组

a = np.array(
[[[1, 2],
[3, 4]],

[[5, 6],
[7, 8]]]
)

我想从这个数组中获取对角线分量,我的意思是,

>> np.array([a[i,i,:] for i in range(min(a.shape[0], a.shape[1]))])
array([[1, 2],
[7, 8]])

有没有更快的方法可以完成与上面相同的操作?

最佳答案

np.diagonal适用于二维以上的数组,您可以使用参数 axis1axis2 指定要查看的轴,对于您的情况,默认值 (axis1=0, axis2 =1)作品:

np.diagonal(a, axis1=0, axis2=1).T
# array([[1, 2],
# [7, 8]])

它也适用于在两个轴上具有不同大小的数组:

a = np.array(
[[[1, 2],
[3, 4]],

[[5, 6],
[7, 8]],

[[9, 10],
[11, 12]]]
)

np.diagonal(a).T
#array([[1, 2],
# [7, 8]])

a = np.array(
[[[1, 2],
[3, 4],
[9, 10]],

[[5, 6],
[7, 8],
[11, 12]]]
)

np.diagonal(a).T
#array([[1, 2],
# [7, 8]])

或者您可以使用advanced indexing :

创建范围索引:

idx = np.arange(min(a.shape[:2]))

idx
# array([0, 1])

使用整数数组索引第一和第二维,使用切片索引第三维:

a[idx, idx, :]
#array([[1, 2],
# [7, 8]])

关于python-3.x - 如何获取 numpy 3-D 数组的对角线分量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com