gpt4 book ai didi

python - 从两个 numpy 数组中查找然后排序的更优化方法

转载 作者:太空宇宙 更新时间:2023-11-03 14:18:43 34 4
gpt4 key购买 nike

为了简单起见,请看下面的小例子。假设我们有 2 组 numpy 数组、值和距离。我想找到大于 1 的值并按相应的距离对它们进行排序。如果存在距离相似的值,我希望首先按照较高的值进行排序。

v = np.array([[1.0,2.0,0.0],[1.0,0.0,0.0],[0.0,0.0,0.0]])
d = np.array([[1.5,1.0,1.5],[1.0,0.0,1.0],[1.5,1.0,1.5]])

indexes = np.argwhere(v >= 1)

list = ( ((d[r,c],v[r,c],(r,c))) for r, c in indexes)

closest_highest = sorted(list,key=lambda t: (t[0],-t[1]))
print(closest_highest)

输出:

[(1.0, 2.0, (0, 1)), (1.0, 1.0, (1, 0)), (1.5, 1.0, (0, 0))]

每个元组包含两个数组的距离、值及其坐标。

是否有更快的方法来仅使用 numpy/向量化计算来完成上述操作?如果没有,是否有更快/更有效的方法来执行以下操作?我真的不需要它来返回元组,只需索引就足够了。即使只是具有最高值的最小距离的索引就足够了。

最佳答案

方法#1:这是一种获取具有最高值的最短距离索引的方法 -

# Get row, col indices for the condition
r,c = np.where(v >= 1)

# Extract corresponding values off d and v
di = d[r,c]

# Get indices (indexable into r,c) corresponding to lowest distance
ld_indx = np.flatnonzero(di == di.min())

# Get max index (based off v) out of the selected indices
max_v_idx = v[r[ld_indx], c[ld_indx]].argmax()

# Get the index (indexable into r,c) with the max one based off v
max_idx = ld_indx[max_v_idx]

# Index into r,c with it
lowest_index_out = (r[max_idx], c[max_idx])

将其视为一个两步过滤过程 - 一旦基于最小 di 值,然后在下一步中基于第一步的 argmax()过滤后选出一位获胜者。 ld_indxmax_v_idx 是两个过滤步骤。 max_idx 是回溯并获取索引的步骤,该索引可用于获取 r,c 的最终索引元组。

方法#2:使用更多屏蔽 -

indexes = np.argwhere(v >= 1)

di = d[indexes[:,0],indexes[:,1]]
valid_mask = di == di.min()
indexes_mask = indexes[valid_mask]

maxv_indx = v[indexes_mask[:,0],indexes_mask[:,1]].argmax()
lowest_index_out = indexes[valid_mask][maxv_indx]

关于python - 从两个 numpy 数组中查找然后排序的更优化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48083885/

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