python - 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)]))
但是有没有更快的方法没有循环?
解决方案
虽然不是真正摆脱循环,但这里有一种方法可以做到这一点:
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
推荐阅读
- java - 如何从 Java 检索数据到 sqlite 以检查数据是否已经存在并更新数据是否匹配
- javascript - 如何使用带有适当缩进的 html 元素的 curl 来抓取网站
- apache-pig - 如何检查元组是否包含 Apache Pig 中的元素?
- r - 检验假设 R 中今年的通过率是否显着低于 0.5?
- java - 如何在 SpringBoot 中制作可以重定向到 url 的 REST api
- python - 将 pandas 数据框转换为字典,其中一列键和另一列值
- sql - 过去 n 天的 Redshift SQL 事件数
- r - 是否有 R 函数可以在 2 个条件下使用 ifelse
- spring-boot - 有没有办法使用 jdbctemplate 将从文件中读取的 sql 批量插入到数据库中?
- django - Django 电子商务:未找到带有参数 '('',)' 的 'cart_add' 的反向。尝试了 1 种模式:['cart/add/(?P
[0-9]+)/$']