在GeoDataFrame中创建列并向其中写入新值

时间:2019-07-04 17:21:11

标签: python gis geopandas

我试图将一列添加到以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不兼容的索引器”错误

1 个答案:

答案 0 :(得分:0)

我尝试遵循您的代码,如果我没记错的话,您可以通过做一些细微的改动来实现您打算做的事情:

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