簡體   English   中英

轉換 function 以減少計算時間(python)

[英]Convert a function in order to reduce the computation time (python)

我正在嘗試將 function 轉換為更優化的方式,以減少計算時間。 更具體地說,我想保持 plot1 的每個點與 plot2 的所有點(其中 plot1、plot2 具有緯度、經度列的數據幀)相比的最小半正弦距離。 這是我的代碼:

def calculate_min_haversine_distance(plot1, plot2):

    for index,row in plot1.iterrows():
        minimum = 100000000
        for index2, row2 in plot2.iterrows():
            dis = haversine_distance(row.latitude, row.longitude, row2.latitude, row2.longitude) 
            if (dis<minimum):
                minimum=dis
        plot1.loc(index,'Min Haversine Distance') = minimum

    return plot1

我不確定如何擺脫第一個循環,但這應該可以幫助您擺脫第二個循環:

def calculate_min_haversine_distance(plot1, plot2):
    for index,row in plot1.iterrows():
        plot2['dist'] = plot2.apply(lambda x: haversine_distance(row.latitude, row.longitude, x.latitude, x.longitude), axis=1)
        plot1.loc[index,'Min Haversine Distance'] = min(plot2['dist'])
    plot2.drop('dist', axis=1, inplace=True) # Delete the temporary column created
    return plot1

我會嘗試做這樣的事情:我希望它有所幫助。

import pandas as pd
import numpy as np


df1 = pd.DataFrame(data={'lat': [1,2,3,4], 'lon': [5,6,7,8]})
df2 = pd.DataFrame(data={'lat': [9,10,11,12], 'lon': [13,14,15,16]})
df1['key'], df2['key'] = 1,1

df_c = pd.merge(df1, df2, on='key').drop('key', axis=1)

# below function is copied from: https://stackoverflow.com/a/43577275/4450090
def haversine(lat1, lon1, lat2, lon2, to_radians=True, earth_radius=6371):
    if to_radians:
        lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])

    a = np.sin((lat2-lat1)/2.0)**2 + \
        np.cos(lat1) * np.cos(lat2) * np.sin((lon2-lon1)/2.0)**2

    return earth_radius * 2 * np.arcsin(np.sqrt(a))

df_c['dist'] = df_c.apply(lambda x: haversine(x['lat_x'], x['lon_x'], x['lat_y'], x['lon_y']), axis=1)
min_val = 1000000
df_c['dist'] = df_c['dist'].apply(lambda x: x if x < min_val else min_val)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM