如何在给定具有两个 lat/long 值的 DataFrame 的情况下使用 geopandas return 多行

How to return multiple lines with geopandas given a DataFrame with two lat/long values

我构建了一个 python 程序,它将通过我的电子邮件进行虹吸并检索 lat/long 对与未来分析相关的工作站点。目前我有以下数据框 returned.

                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 函数将这些点变成多线,并最终变成多边形。使用文档,我能够使用一组 lat/long 对创建 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)

但我似乎无法弄清楚如何使用 lat/long 对将这些值 return 作为行。

我期待在文档中看到一个与 "points_from_xy" 相当的函数,它会生成一个多行 GeoDataFrame,但我认为不存在任何这样的函数。

任何智慧的话语and/or文档链接都将非常有用。

没有用于精确转换的预构建方法,因此您必须自己创建几何对象。我假设您的意思是 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 机器,一旦你特别需要它的 processing/plotting 动力。