首页 > 解决方案 > Numpy:在没有循环的情况下获取索引中的最小值?

问题描述

假设我有以下数组:

distance = np.array([2, 3, 5, 4, 8, 2, 3])
idx = np.array([0, 0, 1, 1, 1, 2, 2 ])

现在我想要一个索引内的最小距离。所以我的目标是:

result = [2, 4, 2]

我现在唯一的想法是这样的:

for i in idx_unique:
    result.append(np.amin(distances[np.argwhere(idx = i)]))

但是有没有更快的方法没有循环?

标签: pythonnumpy

解决方案


虽然不是真正摆脱循环,但这里有一种方法可以做到这一点:

import numpy as np

distance = np.array([2, 3, 5, 4, 8, 2, 3])
idx = np.array([0, 0, 1, 1, 1, 2, 2 ])

t = np.split(distance, np.where(idx[:-1] != idx[1:])[0] + 1)
print([np.min(x) for x in t])

实际上,这并没有提供任何改进,因为 OP 的解决方案和这个解决方案具有相同的运行时间:

res1 = []
def soln1():
    for i in idx_unique:
        res1.append(np.amin(distances[np.argwhere(idx = i)]))

def soln2():
    t = np.split(distance, np.where(idx[:-1] != idx[1:])[0] + 1)
    res2 = [np.min(x) for x in t]

Timeit 给出:

%timeit soln1
#10000000 loops, best of 5: 24.3 ns per loop
%timeit soln2
#10000000 loops, best of 5: 24.3 ns per loop

推荐阅读