![](/img/trans.png)
[英]Find the intersect or nearest geo coordinates from pandas dataframe columns
[英]get nearest coordinates from pandas df from centroid of coordinates
我有一只熊貓df
id x_value y_value
100 1 2
200 3 1
300 5 3
400 3 6
500 3.2 3.5
600 4.5 3
我想從這些坐標對中找到中間點,這樣它將從中點坐標返回最接近的數據幀行。
def get_centroid(df):
lat_mean = df['x_value'].mean()
lat_mean = df['x_value'].iloc[(df['x_value']-lat_mean).abs().argsort([:1]].tolist()[0]
long_mean = df['y_value'].mean()
long_mean = df['y_value'].iloc[(df['y_value']-long_mean).abs().argsort()[:1]].tolist()[0]
return([lat_mean,long_mean])
但這種方法是錯誤的,因為我不會得到精確的df對。
這樣做還有其他辦法嗎?
中心將是你可以得到的平均x和y
df.mean()
x_value 3.283333
y_value 3.083333
dtype: float64
這可以獲得距平均值的最小平方距離的位置
df.sub(df.mean()).pow(2).sum(1).idxmin()
500
這會讓你排成一行
df.loc[[df.sub(df.mean()).pow(2).sum(1).idxmin()]]
x_value y_value
id
500 3.2 3.5
建立
df = pd.DataFrame({
'x_value': [1.0, 3.0, 5.0, 3.0, 3.2, 4.5],
'y_value': [2.0, 1.0, 3.0, 6.0, 3.5, 3.0]
}, pd.Index([100, 200, 300, 400, 500, 600], name='id')
)
如果您正在尋找最小的歐幾里德距離,您可以計算每行的中心距離並選擇最小的距離:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame([{'y': 2.0, 'x': 1.0, 'id': 100}, {'y': 1.0, 'x': 3.0, 'id': 200}, {'y': 3.0, 'x': 5.0, 'id': 300}, {'y': 6.0, 'x': 3.0, 'id': 400}, {'y': 3.5, 'x': 3.2, 'id': 500}, {'y': 3.0, 'x': 4.5, 'id': 600}])
>>> df = df.set_index('id')
>>> df
x y
id
100 1.0 2.0
200 3.0 1.0
300 5.0 3.0
400 3.0 6.0
500 3.2 3.5
600 4.5 3.0
>>> center_x, center_y = df.mean()
>>> np.sqrt((center_x - df['x'])**2 + (center_y - df['y'])**2)
id
100 2.527295
200 2.102512
300 1.718688
400 2.930396
500 0.424918
600 1.219517
dtype: float64
>>> (np.sqrt((center_x - df['x'])**2 + (center_y - df['y'])**2)).idxmin()
500
>>> df.loc[(np.sqrt((center_x - df['x'])**2 + (center_y - df['y'])**2)).idxmin()]
x 3.2
y 3.5
Name: 500, dtype: float64
據我所知,這與答案的方法相同,但不夠簡潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.