簡體   English   中英

在 Python / GeoPandas 中組合 shapefile

[英]Combining shapefiles in Python / GeoPandas

我有三個相互重疊的多邊形 shapefile。 讓我們稱他們為:

  • file_one.shp(多邊形名稱為 1)
  • file_two.shp(多邊形名稱為 2)
  • file_three.shp(多邊形名稱為 3)

我想將它們結合起來並保持這樣的值。

在此處輸入圖片說明

請問如何在Python中實現結果(如圖所示)?

謝謝!

如果您只想從您提到的文件創建一個 shapefile,您可以嘗試以下代碼(我假設 shapefiles 具有相同的列)。

import pandas as pd
import geopandas as gpd

gdf1 = gpd.read_file('file_one.shp')
gdf2 = gpd.read_file('file_two.shp')
gdf3 = gpd.read_file('file_three.shp')

gdf = gpd.GeoDataFrame(pd.concat([gdf1, gdf2, gdf3]))

首先,讓我們生成一些數據進行演示:

import geopandas as gpd
from shapely.geometry import Point
shp1 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(3)], 'name': ['Shape 1']})
shp2 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(2)], 'name': ['Shape 2']})
shp3 = gpd.GeoDataFrame({'geometry': [Point(1, 1).buffer(1)], 'name': ['Shape 3']})

現在取所有的對稱差異,但最小的形狀,可以保持原樣:

diffs = []
gdfs = [shp1, shp2, shp3]
for idx, gdf in enumerate(gdfs):
    if idx < 2:
        diffs.append(gdf.symmetric_difference(gdfs[idx+1]).iloc[0])
diffs.append(shp3.iloc[0].geometry)

好了,現在您有了所需的形狀作為差異列表。 如果您想將它們組合到一個 GeoDataFrame 中,只需執行以下操作:

all_shapes = gpd.GeoDataFrame(geometry=diffs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM