需要帮助抑制 Python 代码执行中的特定 UserWarning

问题描述 投票:0回答:1

我在执行 Python 代码期间遇到持续的“UserWarning”,尽管尝试了各种方法,但仍无法抑制它。我希望获得有关解决此问题的一些指导。

上下文如下:

我的代码中有一个名为 get_water_data 的函数,它下载水数据并执行一些操作。然而,在执行这个函数的过程中,我遇到了以下警告:

UserWarning: keep_geom_type can not be called on a mixed type GeoDataFrame.

功能如下:

def get_water_data(north, south, east, west, mask_gdf):
 print("Download water_data in progress....")

 tags= {"natural":["water"], "waterway":["river"]}
 gdf = ox.features_from_bbox(north, south, east, west, tags)
 gdf_reproj = ox.project_gdf(gdf, to_crs="EPSG:3857")

 gdf_clipped= gpd.clip(gdf_reproj, mask_gdf, keep_geom_type=True)
 gdf_clipped = gdf_clipped[(gdf_clipped['geometry'].geom_type =='Polygon') | (gdf_clipped['geometry'].geom_type == 'LineString')]

 print("water_data ...OK\n")
 return gdf_clipped

我尝试使用通常推荐的方法来抑制此警告,包括:

1.在所有其他模块之前导入 warnings 模块,并在函数范围内使用 warnings.filterwarnings("ignore", Category=UserWarning, module="geopandas") ,如下所示:

import warnings
import geopandas as gpd

def get_water_data(north, south, east, west, mask_gdf):
 warnings.filterwarnings("ignore", category=UserWarning, module="geopandas").
 print("Download water_data in progress....")

 tags= {"natural":["water"], "waterway":["river"]}
 gdf = ox.features_from_bbox(north, south, east, west, tags)
 gdf_reproj = ox.project_gdf(gdf, to_crs="EPSG:3857")

 gdf_clipped= gpd.clip(gdf_reproj, mask_gdf, keep_geom_type=True)
 gdf_clipped = gdf_clipped[(gdf_clipped['geometry'].geom_type =='Polygon') | (gdf_clipped['geometry'].geom_type == 'LineString')]

 print("water_data ...OK\n")
 return gdf_clipped

2.尝试使用 warnings.filterwarnings("ignore") 完全抑制警告。 但是,警告仍然存在。

有人可以提供有效抑制此特定 UserWarning 的指导吗?任何见解或替代方法将不胜感激。

提前谢谢您!

python warnings geopandas
1个回答
0
投票

问题来自这一行:

 gdf_clipped= gpd.clip(gdf_reproj, mask_gdf, keep_geom_type=True)

文档指出:

如果为 True,则在相交时仅返回原始类型的几何图形,从而导致多种几何类型或几何集合。如果为 False,则返回所有生成的几何图形(可能是混合类型)。

在您的情况下,您肯定有混合几何类型,并且无法满足

True
上的
keep_geom_type
条件。

我想说你首先需要使用

gdf.geom_type.unique()
检查几何类型,然后分别处理每种类型以确保没有警告,例如:

gdf_polygon = gdf[gdf.geom_type == 'Polygon']
gdf_line = gdf[gdf.geom_type == 'LineString']
gdf_point = gdf[gdf.geom_type == 'Point']

警告通常意味着存在非批评性问题,但仍然存在。

© www.soinside.com 2019 - 2024. All rights reserved.