【发布时间】:2020-08-05 11:29:39
【问题描述】:
我有Wrocław city borders 和Wroclaw bicycle paths 的shp 文件。我想计算每个区有多少公里的自行车道。
计算我只想选择每个区域中的路径,然后对它们的长度求和。我尝试了 4 种方法,但都失败了。为了示例方便,我们只使用第一个区域
import geopandas as gpd
#For ease of the example, lets use only first district
district = city_bounderies.iloc[[0], ]
type(district)
#we can see that there are some bicycle paths in this district
plot = district.plot( color = "red")
bicycle_path.plot(ax = plot)
#for example bicycle path 8982 id in the district
plot = district.plot( color = "red")
bicycle_path.iloc[[8982],].plot(ax = plot)
1.方法中的 geopandas - 基于我读到的 here
district_bicycle_path = bicycle_path[bicycle_path.geometry.within(district)]
但结果我得到了空的数据框
2。 geopandas 剪辑方法 - 基于我阅读的内容here
bicycle_path.clip(district)
district.clip(bicycle_path)
但是他们都给出了错误:
# TypeError: float() argument must be a string or a number, not 'LineString'
3. geopandas 擦除方法 - 基于我阅读的内容here
bicycle_path.Erase(district)
但这会产生错误:
#error AttributeError: 'GeoDataFrame' object has no attribute 'Erase'
4. geopandas 函数叠加
gpd.overlay(district, bicycle_path, how='intersection')
错误:
#error TypeError: overlay only takes GeoDataFrames with (multi)polygon geometries.
编辑:
我正在基于description how to create shp添加更小的、可重现的示例
初始数据集看起来像这样
import geopandas as gpd
from shapely.geometry import Point, Polygon, LineString
# Create an empty geopandas GeoDataFrame
Sample_district = gpd.GeoDataFrame()
Sample_line = gpd.GeoDataFrame()
# Create a new column called 'geometry' to the GeoDataFrame
Sample_district['geometry'] = None
Sample_line['geometry'] = None
# Coordinates of the sample data
coordinates_district = [(0, 0), (2, 0), (2, 2), (0, 2)]
coordinates_bicycleroad = [(-1, 1), (3, 1)]
# Create a Shapely polygon from the coordinate-tuple list
poly = Polygon(coordinates_district)
line = LineString(coordinates_bicycleroad)
# Insert the polygon into 'geometry' -column at index 0
Sample_district.loc[0, 'geometry'] = poly
Sample_line.loc[0, 'geometry'] = line
#Plot
p = Sample_district.plot(color = "blue")
Sample_line.plot(ax = p, color = "red")
但我想删除所有在该地区以外的自行车道,看起来像这样:
Sample_line_desired = gpd.GeoDataFrame()
Sample_line_desired['geometry'] = None
coordinates_bicycleroad_desired = [(0, 1), (2, 1)]
line_desired = LineString(coordinates_bicycleroad_desired)
Sample_line_desired.loc[0, 'geometry'] = line_desired
p = Sample_district.plot(color = "blue")
Sample_line_desired.plot(ax = p, color = "black")
【问题讨论】:
-
如果没有可运行的示例,就无法为您提供帮助。模拟一些非常简单的几何图形(直线、正方形和三角形),看看你的代码是否有效
-
@PaulH 原始数据在提供的链接中。我还可以在当天晚些时候准备人工样本数据
-
@PaulH 我编辑了问题并添加了一些非常简单的几何图形的可运行示例
-
在范围操作(剪辑或内部)之后没有获得数据的一个常见原因是两个地理数据框没有相同的坐标参考系 (CRS)。因此,在您执行其中任何一项操作之前,请确保它们具有匹配的 CRS,如果没有,请将一个重新投影到其他操作以使它们匹配。
标签: python shapefile geopandas