gpt4 book ai didi

python - 将 numpy 函数的输出放入数组的对角线中

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

我想获取一个数组的行和并将输出放入另一个数组的对角线中。出于性能原因,我想使用 np.sum 函数的 out 参数。

mat1 = np.array([[0.5, 0.5],[0.6, 0.4]])

mat2 = np.zeros([2,2])

mat3 = np.zeros([2,2])

如果我想将mat1的行总和放入mat2的第一行,我可以这样做:

np.sum(mat1, axis=1, out = mat2[0])

mat2
#array([[ 1., 1.],
# [ 0., 0.]])

但是,如果我想将总和放入 mat3对角线索引中,我似乎无法这样做。

np.sum(mat1, axis=1, out = mat3[np.diag_indices(2)])

mat3
#array([[ 0., 0.],
# [ 0., 0.]])

当然,以下方法有效,但我想使用np.sumout参数

mat3[np.diag_indices(2)] = np.sum(mat1, axis=1)

mat3
#array([[ 1., 0.],
# [ 0., 1.]])

有人可以解释一下 out 参数不接受数组对角线索引作为有效输出的行为吗?

最佳答案

NumPy 有两种类型的索引:基本索引和高级索引。

基本索引是指当索引表达式仅使用整数、切片、...None(又名 np.newaxis )。这可以完全通过偏移量和步幅的简单操作来实现,因此当基本索引返回数组时,结果数组始终是原始数据的 View 。写入 View 会写入原始数组。

当您使用数组进行索引时,如 mat3[np.diag_indices(2)] 中所示,您将获得高级索引。高级索引不能以返回原始数据 View 的方式完成;它总是从原始数组中复制数据。这意味着当您尝试使用副本作为 out 参数时:

np.sum(mat1, axis=1, out = mat3[np.diag_indices(2)])

数据被放入副本中,但原始数组不受影响。

<小时/>

我们现在应该能够使用 np.diagonal 来实现此目的,但即使文档说 np.diagonal 的输出可以在 NumPy 中写入1.10,使其可写的相关功能是still in limbo 。最好不要为此使用 out 参数:

mat3[np.diag_indices(2)] = np.sum(mat1, axis=1)

关于python - 将 numpy 函数的输出放入数组的对角线中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068638/

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