给定具有两个纬度/经度值的数据帧,如何使用 geopandas 返回多行

问题描述

我构建了一个 Python 程序,该程序将通过我的电子邮件进行抽取,并检索与未来分析相关的纬度/经度对工作地点。目前我返回了以下数据帧。

                lat1              long1              lat2              long2
0          29.886283         -97.932083         29.892553         -97.921784
1          29.890503         -97.940304         29.891903         -97.938405
2           30.56325         -97.661213         30.570474         -97.651814
3          29.890692         -97.954414         29.891938         -97.952977
4          29.890564         -97.938196         29.892173         -97.936506
..               ...                ...               ...                ...
63  29.8900381016903  -97.9450610026556  29.8906241085088  -97.9442241534448
64  29.8847283631397  -97.9325702241829  29.8873980640358  -97.9291477254781
65         30.556555         -97.659824         30.569138         -97.650855
66         30.556555         -97.659824         30.569138         -97.650855
67         29.890564         -97.938196         29.892173         -97.936506
[68 rows x 4 columns]

我的问题是我无法弄清楚如何使用 GeoSeries.envelope 函数将这些点变成多线,并最终变成多边形。使用文档,我能够使用一组经纬度对创建 GeoDataFrame 点,就像这样......


print(df)
gdf = geopandas.GeoDataFrame(
    df,geometry=geopandas.points_from_xy(df.long1,df.lat1)) #df.lat2,df.long2))
print(gdf.head())

world = geopandas.read_file(geopandas.datasets.get_path(('naturalearth_lowres')))
ax = world[world.continent == 'north America'].plot(
    color = 'white',edgecolor = 'black')

gdf.plot(ax = ax,color='green')

plt.show()

这给出了以下输出

0  29.886283  -97.932083  29.892553  -97.921784  POINT (-97.93208 29.88628)
1  29.890503  -97.940304  29.891903  -97.938405  POINT (-97.94030 29.89050)
2   30.56325  -97.661213  30.570474  -97.651814  POINT (-97.66121 30.56325)
3  29.890692  -97.954414  29.891938  -97.952977  POINT (-97.95441 29.89069)
4  29.890564  -97.938196  29.892173  -97.936506  POINT (-97.93820 29.89056)

但我似乎无法弄清楚如何使用经纬度对将这些值作为线返回。

我期待在文档中看到一个"points_from_xy" 类似的函数生成一个多线 GeoDataFrame,但我不相信任何这样的函数存在。

任何智慧之言和/或文档链接都会非常受欢迎。

解决方法

没有用于精确变换的预构建方法,因此您必须自己创建几何对象。我假设您的意思是 DataFrame 中每行一个 LineString 对象。只需少量输入,您就可以使用强大的 apply 方法创建这样一个列。

from shapely.geomtry import LineString
series = df.apply(
    lambda r: LineString([
         (r['long1'],r['lat1']),(r['long2'],r['lat2'])
    ]),axis=1
)

然后将其转换为 GeoSeries:

In [28]: geopandas.GeoSeries(series)
Out[28]:
0    LINESTRING (29.886 -97.932,29.893 -97.922)
1    LINESTRING (29.891 -97.940,29.892 -97.938)
2    LINESTRING (30.563 -97.661,30.570 -97.652)
3    LINESTRING (29.891 -97.954,29.892 -97.953)
4    LINESTRING (29.891 -97.938,29.892 -97.937)
dtype: geometry

如果我最初将坐标作为一个简单的 Python 数据结构(例如元组列表),我可能会首先准备一个简单的 LineString 对象列表,并且只有在您特别需要时才将其放入 (geo)pandas 机器中它的处理/绘图能力。