如何处理这些pandas错误消息?

时间:2018-02-20 17:12:23

标签: python-3.x pandas

通常在使用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)

在编写大型脚本时,我发现我的代码中很难知道警告的来源。

那么如何判断我的源代码的哪一行会生成警告消息?

2 个答案:

答案 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')

您可以在此处详细了解如何使用pdbhttps://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