如何为字典内的GeoDataFrame应用函数并创建'x'字段?
问题描述
我有一个名为var_holder3的字典,其values是GeoDataFrame,keys是对应GeoDataFrame的变量名。我需要应用getPolyCoords函数,为这些GeoDataFrame创建'x'字段。函数定义如下:
def getPolyCoords(row, geom, coord_type): exterior = row[geom].exterior if coord_type == 'x': return list( exterior.coords.xy[0] ) elif coord_type == 'y': return list( exterior.coords.xy[1] )
我尝试了以下代码:
for x in var_holder3: var_holder3[x]['x'].apply(getPolyCoords, geom='geometry', coord_type='x', axis=1)
期望得到带有新字段'x'的GeoDataFrame,但出现KeyError: 'x'错误,错误栈信息如下:
Traceback (most recent call last): File "/home/kevin1/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3803, in get_loc return self._engine.get_loc(casted_key) File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 165, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 5745, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 5753, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'x' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/home/kevin1/anaconda3/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1415, in __getitem__ result = super().__getitem__(key) File "/home/kevin1/anaconda3/lib/python3.9/site-packages/pandas/core/frame.py", line 3805, in __getitem__ indexer = self.columns.get_loc(key) File "/home/kevin1/anaconda3/lib/python3.9/site-packages/pandas/core/indexes/base.py", line 3805, in get_loc raise KeyError(key) from err KeyError: 'x'
解决方法
- 错误原因:代码中提前访问了还未创建的
'x'字段(var_holder3[x]['x']),此时该字段不存在,触发KeyError。正确逻辑是先对整个GeoDataFrame调用apply计算结果,再将结果赋值给新的'x'字段。 - 修正后的代码:
for x in var_holder3: # 对GeoDataFrame执行apply,将结果赋值给新字段'x' var_holder3[x]['x'] = var_holder3[x].apply(getPolyCoords, geom='geometry', coord_type='x', axis=1)
执行后,每个GeoDataFrame都会新增'x'字段,存储对应多边形外部轮廓的x坐标列表。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

