我遇到这个问题,我需要获取数组的一个元素,使该元素与索引较高的元素之间的总和分别。我已经用 for 循环完成了此操作,例如:
sumtot = np.array([])
for j in range(0,len(matpos)-1):
sum = matpos[j] + matpos[j+1:]
sumtot = np.append(sumtot, sum)
但这需要大量的计算时间,因为数组 matpos
是一个非常大的数组,所以我想是否有一种方法可以在不使用 for
循环的情况下完成此操作.
一个简单的示例是:
-输入:
matpos = np.array([0, 1, 2, 3])
-输出
sumtot = np.array([1, 2, 3, 3, 4, 5])
这是[0+1, 0+2, 0+3, 1+2, 1+3, 2+3]
非常感谢大家!
最佳答案
要获取所需的数组,您可以使用类似 np.triu_indices
的内容进行一些额外的操作:
r, c = np.triu_indices(len(matpos), 1)
totsum = matpos[r] + matpos[c]
这可能是您所能理解的最清晰的内容。如果您想要一行,您可以堆叠索引并将结果相加:
totsum = matpos[np.stack(np.triu_indices(len(matpos), 1))].sum(0)
请注意,这些术语的总结如下:
[matpos[0], matpos[0], matpos[0], ...] + [matpos[1], matpos[2], matpos[3], ...]
[matpos[1], matpos[1], ...] + [matpos[2], matpos[3], ...]
[matpos[2], ...] + [matpos[3], ...]
所选索引和重复次数与triu_indices
(列减一)的结果完全对应,该结果返回矩阵上三角形的索引。
另一种表述:
r, c = np.triu_indices(len(matpos) - 1)
totsum = matpos[r] + matpos[c + 1]
或者
totsum = matpos[np.stack(np.triu_indices(len(matpos) - 1), -1) + [0, 1]].sum(1)
关于python - 无需 for 循环即可对数组元素进行运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66125483/