我无法将
geopandas.GeoDataFrame
中包含几何数据的现有列指定为 geopandas 识别的活动 geometry
列。
这是我的设置:
from geopandas import GeoDataFrame as gdf
from shapely.geometry import Polygon
from shapely.geometry import Point
square = Polygon([[0,0], [0,1], [1,1], [1,0]])
triangle = Polygon([[2,0], [4,0], [3,1]])
figury = gdf([[square, "kwadrat", Point([0.5,0.5])],
[triangle, "trójkąt", Point([3,0.3])]],
columns=["shape", "name", "center"])
然后,当我尝试使用以下方法将 shape
或
center
列指定为活动几何图形(根据 GeoPandas 文档):
figury.set_geometry("shape")
# or
figury.set_geometry("center")
我遇到了(相当讽刺的)错误:
AttributeError: You are calling a geospatial method on the GeoDataFrame, but
the active geometry column to use has not been set.
There are no existing columns with geometry data type. You can add a geometry
column as the active geometry column with df.set_geometry.
我的问题是,“我如何让它发挥作用?”,或者更确切地说,“我做错了什么?”
一个明显的解决方法是在创建
geometry
时命名相关列 GeoDataFrame
,但这只能“有效”,而且只能一次。
任何进一步尝试使用
gdf.set_geometry
分配另一列,或将另一列重命名为“几何”都将拒绝工作(该列已重命名为 为“几何”,但 geopandas
仍不将其视为活动几何列) .
创建地理数据框时,尝试在构造函数调用中使用关键字参数来设置几何图形:
figury = gdf(
[
[square, "kwadrat", Point([0.5,0.5])],
[triangle, "trójkąt", Point([3,0.3])]
],
columns=["shape", "name", "center"], geometry='shape')
然后您应该能够根据需要将几何图形设置为其他选项:
figury.set_geometry('center').geometry
>>> 0 POINT (0.50000 0.50000)
>>> 1 POINT (3.00000 0.30000)
>>> Name: center, dtype: geometry