Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在GeoDataFrame中创建列并向其写入新值_Python_Gis_Geopandas - Fatal编程技术网

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

Python 在GeoDataFrame中创建列并向其写入新值,python,gis,geopandas,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)] scala

我试图将列添加到作为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)
多边形是一种gdf(多边形)。冲突是一个点数据集,也作为gdf读入

还尝试:

polys.conflict.iloc[0] = subset

获取“带有数据帧的不兼容索引器”错误

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

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
中提供的空间索引(可对此进行完整解释):


LeandroOrdonez,在这两种情况下,冲突的值仍然会导致每个多边形的“无”。没有值被写回已创建的列。然后,您可能必须检查
poly
conflict
地理数据帧之间是否存在实际交点,以及在中读取它们时是否使用相同的坐标参考系(CRS)。加载两个数据集后,可以通过运行以下两行代码来确保:
polys=polys.to_crs({'init':'epsg:3857'})
conflict=conflict.to_crs({'init':'epsg:3857'})
冲突文件没有项目。我已经验证了Polys文件是epsg:4326,并根据以下命令在读取冲突文件时将此投影分配给冲突文件:Conflict.crs={'init':'epsg:4326'}冲突点和多边形中绝对存在重叠,因为我在Python中以本机方式绘制冲突点和多边形,并且可以看到冲突点和多边形,并将其写入在QGIS中显示重叠的形状文件。尽管如此,冲突一栏还是没有列出所有的多边形。我做过类似的事情,我认为,它是有效的。您可以查看它
iterrows
创建每行的副本。您需要使用
polys.at[index,'conflict']分配正在处理的值。
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