python找到两个numpy数组的交点 [英] python find the intersection point of two numpy array

查看:438
本文介绍了python找到两个numpy数组的交点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个描述一个空间曲线的numpy数组,它们在一个点上相交,并且我想在两个数组中找到该交点的最接近值,我有这段代码可以正常工作,但是它会大量减慢速度点.

I have two numpy array that describes a spatial curve, that are intersected on one point and I want to find the nearest value in both array for that intersection point, I have this code that works fine but its to slow for large amount of points.

from scipy import spatial
def nearest(arr0, arr1):
    ptos = []
    j = 0
    for i in arr0:
        distance, index = spatial.KDTree(arr1).query(i)
        ptos.append([distance, index, j])
        j += 1
    ptos.sort()
    return (arr1[ptos[0][1]].tolist(), ptos[0][1], ptos[0][2])

结果将为(<point coordinates>,<position in arr1>,<position in arr0>)

推荐答案

您的代码执行了许多您不需要的事情.首先,您需要在每个循环上重建KDtree,这很浪费.同样,query接受点数组,因此无需编写自己的循环.取力器是一个奇怪的数据结构,您不需要它(也不需要对其进行排序).尝试这样的事情.

Your code is doing a lot of things you don't need. First you're rebuilding the KDtree on every loop and that's a waste. Also query takes an array of points, so no need to write your own loop. Ptos is an odd data structure, and you don't need it (and don't need to sort it). Try something like this.

from scipy import spatial

def nearest(arr0, arr1):
    tree = spatial.KDTree(arr1)
    distance, arr1_index = tree.query(arr0)
    best_arr0 = distance.argmin()
    best_arr1 = arr1_index[best_arr0]
    two_closest_points = (arr0[best_arr0], arr1[best_arr1])
    return two_closest_points, best_arr1, best_arr0

如果那还不够快,则需要更详细地描述您的问题,并找出其他搜索算法是否可以更好地解决您的问题.

If that still isn't fast enough, you'll need to describe your problem in more detail and figure out if another search algorithm will work better for your problem.

这篇关于python找到两个numpy数组的交点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆