3
我有一個代碼來計算成對距離和我的數據(X,Y,Z)的殘差。數據非常大(平均7000行),所以我的興趣是代碼效率。我最初的代碼是配對距離和殘差計算優化
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import, numpy as np
from scipy.spatial.distance import pdist, squareform
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
data = pd.read_excel(file_path)
data = np.array(data, dtype=np.float)
npoints, cols = data.shape
pwdistance = np.zeros((npoints, npoints))
pwresidual = np.zeros((npoints, npoints))
for i in range(npoints):
for j in range(npoints):
pwdistance[i][j] = np.sqrt((data[:,0][i]-data[:,0][j])**2 + (data[:,1][i]-data[:,1][j])**2)
pwresidual[i][j] = (data[:,2][i]-data[:,2][j])**2
隨着pwdistance
,我把它改成以下,低於該作品非常好。
pwdistance = squareform(pdist(data[:,:2]))
有沒有計算我pwresidual
的Python的方式,所以我並不需要使用一個循環,使我的代碼運行得更快?
你可以使用'的np.hypot'代替'np.sqrt'和'** 2' –
@FranciscoCouzo看來OP是要求獲得/優化'pwresidual'。我第一次感到困惑:) – Divakar
@Divakar這就是爲什麼我發表評論而不是回答:) –