首页 > 解决方案 > Python,熊猫数据框,坐标的条件格式

问题描述

我有数据框,上面有坐标(记录的路线)。数据框结构是这样的(有更多列):

没有纬度经度高度速度课程日期时间等。

0 59.303758 18.078915 NaN 0.0 114.9 2017/04/01 13:21:48

1 59.303758 18.078915 -8.5 0.0 114.9 2017/04/01 13:21:49

2 59.303758 18.078915 -8.5 0.0 114.9 2017/04/01 13:21:50

.

.

清单还在继续……

我正在尝试从数据框中解析不需要的点。图片上的例子。红线代表数据框中的坐标点,我只想获得绿色字段上的点。

路线

示例代码:

#north
y_1n=59.33551 #point 1 latitude
x_1n=18.02649 #point 1 longitude
y_2n=59.33327 #point 2 latitude
x_2n=18.04500 #point 2 longitude
#south
y_1s=59.33478 #point 3 latitude
x_1s=18.02645 #point 3 longitude
y_2s=59.33246 #point 4 latitude
x_2s=18.04422 #point 4 longitude
#
test = df1[(df1['Latitude'] <= y_1n) & (df1['Latitude'] >= y_2n) &
            (df1['Latitude'] <= y_1s) & (df1['Latitude'] >= y_2s) &
            (df1['Longitude'] >= x_1n) & (df1['Longitude'] <= x_2n) &
            (df1['Longitude'] >= x_1s) & (df1['Longitude'] <= x_2s)
          ]

所以想法是,只有这些预定义的 2 个北和 2 个南点(坐标点)内的数据包含在新数据框中。

使用该代码我设法解析数据,但它远离南北点(仅包括一半街道)。所以它确实过度解析它或发生了一些奇怪的事情..

有没有更好或更有效的方法来做到这一点?

标签: pythonpandasgpscoordinates

解决方案


我确实通过以下方式解决了这个问题..

首先,我创建了 Geopandas Dataframe 并使用 Shapely 创建多边形。然后我将多边形添加到数据框中。还添加了对应多边形的位置。

import geopandas as gpd
from shapely.geometry import Point, Polygon, LineString
polygon = gpd.GeoDataFrame()
coord = [(18.02649,59.33551),(18.04500,59.33327),(18.02645,59.33478), 
         (18.04422,59.33246)]

polygon.loc[0, 'geometry'] = Polygon(coord)
polygon.loc[0, 'Location'] = 'Fleminggatan'

然后我从 Pandas DataFrame 复制到 Geopandas Dataframe。

df2 = gpd.GeoDataFrame(df1)

之后,我为 DataFrame 制作了新系列,女巫结合了纬度和经度系列。

df2['geometry'] = [Point(xy) for xy in zip(df2.Longitude, df2.Latitude)]

然后我使用了 Geopandas 空间连接。(op) 在这个 cos 中并不重要,因为我将点连接到多边形。如果这些是线条,那会有所作为。

df3 = gpd.sjoin(df2,polygon, how='inner', op='intersects')

在此之后,我留下了 DataFrame,其中包含所需位置的数据。


推荐阅读