通常在使用pandas时,我会收到这样的UserWarning和PerformanceWarning消息:
C:\Users\User\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py:558: UserWarning: merging between different levels can give an unintended result (2 levels on the left, 1 on the right)
warnings.warn(msg, UserWarning)
C:\Users\User\Anaconda3\lib\site-packages\pandas\core\reshape\merge.py:558: UserWarning: merging between different levels can give an unintended result (1 levels on the left, 2 on the right)
warnings.warn(msg, UserWarning)
C:\Users\User\Anaconda3\lib\site-packages\pandas\core\generic.py:2530: PerformanceWarning: dropping on a non-lexsorted multi-index without a level parameter may impact performance.
obj = obj._drop_axis(labels, axis, level=level, errors=errors)
在编写大型脚本时,我发现我的代码中很难知道警告的来源。
那么如何判断我的源代码的哪一行会生成警告消息?
答案 0 :(得分:1)
我经常使用的一种方法是在filterwarnings()
包中配置warnings
方法来过滤要引发的警告,这将使您能够调试它们(例如,使用pdb
) 。要执行此操作,您只需import
warnings
个包,然后在filterwarnings()
上设置warnings
方法即可观看并提出特定警告,如下所示:
import warnings
warnings.filterwarnings('error', category=UserWarning)
warnings.filterwarnings('error', category=PerformanceWarning)
您也可以配置warnings
来发出任何警告,例如:
import warnings
warnings.filterwarnings('error')
您可以在此处详细了解如何使用pdb
:
https://docs.python.org/3/library/pdb.html
答案 1 :(得分:1)
如果您打算解决潜在的问题,则可以在命令行上使用-W
选项将警告变为错误,这将为您提供完整的堆栈跟踪。
从命令行文档中:
-W arg:警告控制; arg是action:message:category:module:lineno 也PYTHONWARNINGS = arg
例如,要捕获以“在不同级别之间合并...”开头的警告,可以运行:
python -Werror:merging myscript.py