【问题标题】:Map numpy array and sum values on positions in another array映射 numpy 数组并在另一个数组中的位置上求和值
【发布时间】:2020-03-19 04:26:18
【问题描述】:

我有 2 个 numpy 数组:

distances = np.array([
    [0, 6, 7, 4, 2],
    [6, 0, 6, 3, 8],
    [7, 6, 0, 9, 3],
    [4, 3, 9, 0, 4],
    [2, 8, 3, 4, 0]
])

path = np.array([3, 1, 2, 0])

path,有一些我想去的地方。每个位置都是distances 的索引。所以在上面的例子中,我访问位置3,然后是1,然后是2,然后是0,然后回到3。为此,我想计算3, 11, 22, 00, 3 的距离总和(路径是封闭的圆圈)。

您可以从distances[3, 1] (= 3) 获得31 之间的距离,从distances[1, 2] (= 6) 获得12 之间的距离等。上面示例中的距离应该是@ 987654339@.

我创建了这个函数:

import time
import numpy as np

distances = np.array([
    [0, 6, 7, 4, 2],
    [6, 0, 6, 3, 8],
    [7, 6, 0, 9, 3],
    [4, 3, 9, 0, 4],
    [2, 8, 3, 4, 0]
])

path = np.array([3, 1, 2, 0])

def get_distance(path):
    distance = 0

    for i in range(len(path) - 1):
        distance += distances[path[i], path[i + 1]]

    distance += distances[path[-1], path[0]]

    return distance

start = time.time()

for i in range(100000):
    get_distance(path)

end = time.time()
print(end - start) # 0.206

它正在工作,但我需要以长路径(例如 50 个位置)多次运行此功能(例如百万次),所以我想优化它。有什么办法吗?

【问题讨论】:

  • @Divakar 为什么不把它变成一个答案呢?
  • @iliar 看起来很简单,但似乎不是骗子。贴出答案。谢谢。

标签: python python-3.x numpy optimization sum


【解决方案1】:

我们可以简单地将索引数组切片并索引到distances 数组中以获得这些特定距离,然后将它们相加得到最终输出。与原始代码一样,我们将分别对最后一对进行求和。因此,它将是-

distances[path[:-1], path[1:]].sum() + distances[path[-1], path[0]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2021-01-29
    • 2017-07-06
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多