解析GeoJSON字符串转GeoDataFrame时处理空要素/空值问题
处理GeoJSON空值导致的GeoDataFrame转换报错
问题背景
现有包含GeoJSON字符串列的Pandas DataFrame,此前通过gpd.GeoDataFrame.from_features([json.loads(feature) for feature in test_features])可正常转换为GeoDataFrame,但近期出现如下报错:
AttributeError: 'NoneType' object has no attribute 'lower'
报错根源是部分GeoJSON Feature的geometry字段为空,或geometry的type为None,导致Shapely无法解析。
解决方案
方案1:过滤无效Feature后转换
先解析所有GeoJSON字符串,过滤掉geometry无效的Feature,再生成GeoDataFrame:
import json import geopandas as gpd valid_features = [] for geo_str in df['Geojson']: try: feature = json.loads(geo_str) # 检查geometry存在且type不为空 if feature.get('geometry') and feature['geometry'].get('type'): valid_features.append(feature) else: print(f"跳过无效Feature:{geo_str[:50]}...") # 打印部分内容便于排查 except json.JSONDecodeError as e: print(f"JSON解析失败:{e},跳过该行") gdf = gpd.GeoDataFrame.from_features(valid_features)
方案2:保留原DataFrame结构,标记无效Geometry
如果需要保留原DataFrame的所有行,仅将无效的Geometry设为None,后续可按需过滤:
import json import geopandas as gpd from shapely.geometry import shape def safe_parse_geometry(geo_str): try: feature = json.loads(geo_str) geom = feature.get('geometry') # 双重校验:geometry存在且type有效 if geom and geom.get('type'): return shape(geom) return None except (json.JSONDecodeError, AttributeError): return None # 生成geometry列 df['geometry'] = df['Geojson'].apply(safe_parse_geometry) # 转换为GeoDataFrame,保留原列 gdf = gpd.GeoDataFrame(df, geometry='geometry') # 可选:过滤掉无有效Geometry的行 gdf = gdf.dropna(subset=['geometry'])
方案3:简化列表推导式(适合小数据量)
如果数据量较小,可直接用列表推导式过滤,但注意会重复解析GeoJSON字符串,大数据量下效率较低:
import json import geopandas as gpd valid_features = [ feat for feat in [json.loads(f) for f in df['Geojson']] if feat.get('geometry') and feat['geometry'].get('type') ] gdf = gpd.GeoDataFrame.from_features(valid_features)
关键检查要点
- 必须校验
geometry字段是否存在且不为None - 额外校验
geometry中的type字段是否有效(避免type为null的情况) - 捕获JSON解析异常,防止单个格式错误的GeoJSON中断整个转换流程
内容的提问来源于stack exchange,提问作者William_Boot
相关产品推荐
相关产品推荐

