如何在多个相同大小的数组上应用复杂函数以在 python 中使用 numpy 创建新的相同大小的数组

我有一个获取 x 和 y 位置并执行最近邻搜索的函数。我想将此函数应用于两个数组,以便我可以获得数组中每个点的函数结果。我在这里给出了一些示例数据和我想应用的实际功能。我还调用了单点函数。我如何将此函数应用于出现在我的数组xs和中的匹配索引处的每个 x,y 对ys?


import scipy.spatial

import scipy

import numpy as np

import pandas as pd



def est_bathymetry(x,y,bathymetry_data,gsl_level=1278.3,n=4):

    

    grid_xy=np.array([x,y]).T

    

    def do_kdtree(grid_xy,points, n):

    #This function gets the kd tree for the sample, then returns the closest

    #points to each grid node as indices

        points=points[:2,:]

        points=list(points.transpose())

        mytree = scipy.spatial.cKDTree(points)

        dist, indexes = mytree.query(grid_xy, k=n, n_jobs=-1)

        return dist, indexes

        

    dist, indexes = do_kdtree(grid_xy,bathymetry_data.iloc[:,0:2].values.T,n)    

    

    avg_bath=np.nanmean(np.take(bathymetry_data['Bathymetry'], indexes))

    

    return avg_bath

    

#create sample data

x=np.linspace(0,10,11,endpoint=True)

xs=np.tile(x,(11,1))


ys=xs.T


np.random.seed(123)



data=pd.DataFrame([np.random.uniform(0,10,100),np.random.uniform(0,10,100),np.random.normal(2000,100,100)]).T

data.columns=['Lat','Long','Bathymetry']



#example of function working on single input

avg_bathymetry=est_bathymetry(x=np.min(xs),y=np.min(ys),bathymetry_data=data)


叮当猫咪
浏览 93回答 1
1回答

UYOU

我发现使用 np.vectorize 我可以矢量化并应用该函数,这个函数实际上是适用的,但我需要删除其他输入。唯一的问题是运行完整数据集需要 225 天。将不得不回到绘图板。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python