python - 在 Pandas DataFrames 中找到最近点

标签 python postgresql pandas

我是 Python 的新手。我在 Postgres 中有下表。这些是具有四个坐标的多边形值,具有相同的 IdZONE 名称我已将此数据存储在名为 df1

的 Python 数据框中
Id  Order   Lat              Lon            Zone
00001   1   50.6373473  3.075029928          A
00001   2   50.63740441 3.075068636          A
00001   3   50.63744285 3.074951754          A 
00001   4   50.63737839 3.074913884          A 
00002   1   50.6376054  3.0750528            B
00002   2   50.6375896  3.0751209            B
00002   3   50.6374239  3.0750246            B
00002   4   50.6374404  3.0749554            B

我有带有 LonLat 值的 Json 数据,我将它们存储在名为 df2 的 python 数据帧中。

Lat                  Lon
50.6375524099   3.07507914474
50.6375714407   3.07508201591

我的任务是将 df2 LatLon 值与 df1 中每个区域的四个坐标进行比较提取区域名称并将其添加到 df2

例如 (50.637552409 3.07507914474) 属于 Zone B

#This is ID with Zone
df1 = pd.read_sql_query("""SELECT * from "zmap" """,con=engine)
#This is with lat,lon values
df2 = pd.read_sql_query("""SELECT * from "E1" """,con=engine)
df2['latlon'] = zip(df2.lat, df2.lon)
zones = [
["A", [[50.637347297, 3.075029928], [50.637404408, 3.075068636], [50.637442847, 3.074951754],[50.637378390, 3.074913884]]]]
for i in range(0, len(zones)):  # for each zone points
    X = mplPath.Path(np.array(zones[i][1]))
    # find if points are Zones
    Y= X.contains_points(df2.latlon.values.tolist())
    # Label points that are in the current zone
    df2[Y, 'zone'] = zones[i][0]

目前我已经为“A”区手动完成了。我需要为 df2 中的坐标生成“区域”。

最佳答案

这听起来像是 scipy cdist 的一个很好的用例, 还讨论了 here .

import pandas as pd
from scipy.spatial.distance import cdist


data1 = {'Lat': pd.Series([50.6373473,50.63740441,50.63744285,50.63737839,50.6376054,50.6375896,50.6374239,50.6374404]),
         'Lon': pd.Series([3.075029928,3.075068636,3.074951754,3.074913884,3.0750528,3.0751209,3.0750246,3.0749554]),
         'Zone': pd.Series(['A','A','A','A','B','B','B','B'])}

data2 = {'Lat': pd.Series([50.6375524099,50.6375714407]),
         'Lon': pd.Series([3.07507914474,3.07508201591])}


def closest_point(point, points):
    """ Find closest point from a list of points. """
    return points[cdist([point], points).argmin()]

def match_value(df, col1, x, col2):
    """ Match value x from col1 row to value in col2. """
    return df[df[col1] == x][col2].values[0]


df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)

df1['point'] = [(x, y) for x,y in zip(df1['Lat'], df1['Lon'])]
df2['point'] = [(x, y) for x,y in zip(df2['Lat'], df2['Lon'])]

df2['closest'] = [closest_point(x, list(df1['point'])) for x in df2['point']]
df2['zone'] = [match_value(df1, 'point', x, 'Zone') for x in df2['closest']]

print(df2)
#    Lat        Lon       point                           closest                  zone
# 0  50.637552  3.075079  (50.6375524099, 3.07507914474)  (50.6375896, 3.0751209)  B
# 1  50.637571  3.075082  (50.6375714407, 3.07508201591)  (50.6375896, 3.0751209)  B

关于python - 在 Pandas DataFrames 中找到最近点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38965720/

相关文章:

postgresql - postgres 的 nls_date_format

PostgreSQL 中的 SQL patindex 等价物

python-requests 发出 GET 而不是 POST 请求

python - 将相同键的行组合成单个数组

php - postgresql 最长执行时间

python - 在 DataFrameGroupBy 对象的组内进行切片

python - 如何将所有列放在 Pandas 的嵌套列下

python - Pandas 中的空数据框

Python:获取列表中出现次数最多的项目

python:我可以将变量设置为等于其自身的函数吗?