【问题标题】:Create column in GeoDataFrame and write new value to it在 GeoDataFrame 中创建列并向其写入新值
【发布时间】:2019-07-04 17:21:11
【问题描述】:

我正在尝试向作为 GeoDataFrame 读取的 shapefile 添加一列,并使用从点数据集派生的简单计数填充该列。当我这样做时,该列充满了 NaN,这让我相信它是一个需要用 iloc 引用而不是标量的系列。

polys["conflict"] = None
for index, row in polys.iterrows():
    polygon = polys.geometry[0]
    subset = conflict[conflict.within(polygon)]
    scalar = subset.iloc[0]
    polys = polys.assign(conflict=subset)

polys 是一个 gdf(多边形)。冲突是一个点数据集,也作为 gdf ​​读入。

也试过了:

polys.conflict.iloc[0] = subset

获取“与 DataFrame 不兼容的索引器”错误

【问题讨论】:

    标签: python gis geopandas


    【解决方案1】:

    我尝试按照您的代码进行操作,如果我没记错的话,您可以通过进行一些细微的更改来实现您的目标:

    polys["conflict"] = None
    for index, row in polys.iterrows():
        polygon = row.geometry
        subset = conflict[conflict.within(polygon)].shape[0] # gets the count of conflict points inside the polygon
        row['conflict'] = subset
    

    另一种更有效的方法是使用geopandas'GeoDataFrame 中提供的空间索引(对此可用here 的完整说明):

    polys["conflict"] = None
    
    conflict_sindex = conflict.sindex
    for index, row in polys.iterrows():
        possible_matches_index = list(conflict_sindex.intersection(row.geometry.bounds))
        possible_matches = conflict.iloc[possible_matches_index]
        precise_matches = possible_matches[possible_matches.intersects(row.geometry)]
        if not precise_matches.empty:
            res = precise_matches.shape[0] # gets the count of conflict points inside the polygon
            row['conflict'] = res
    

    【讨论】:

    • LeandroOrdonez,在这两种情况下,Conflict 的值仍然会导致每个多边形的“无”。没有值被写回创建的列。
    • 那么您可能需要检查polysconflict 地理数据框之间是否存在交集,以及在读取它们时是否使用相同的坐标参考系统 (CRS)。您可以通过在加载两个数据集后运行以下两行代码来确保:polys = polys.to_crs({'init': 'epsg:3857'})conflict = conflict.to_crs({'init': 'epsg:3857'})
    • 冲突文件没有项目。我已经验证 Polys 文件是 epsg:4326 并在按照以下内容读取它时将此投影分配给冲突文件:conflict.crs = {'init':'epsg:4326'} 冲突点绝对存在重叠和多边形,因为我在 Python 中本地绘制它并且可以看到它并将其写出到 shapefile 中,这些 shapefile 也显示了 QGIS 中的重叠。尽管如此,所有多边形的冲突列都显示为 None。
    • 我认为我做过类似的事情,而且效果很好。你可以看看here
    • iterrows 创建每一行的副本。您需要使用 polys.at[index, 'conflict'] thispointer.com/… 分配您正在处理的值
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2020-05-29
    • 2021-10-18
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多