捕获numpy ComplexWarning作为异常

2024-10-02 10:18:42 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下示例:

>>> import numpy as np
>>> a = np.array([1.0, 2.1j])
>>> b = np.array(a, dtype=np.float64)
/Users/goerz/anaconda3/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
  #!/Users/goerz/anaconda3/bin/python

如何将ComplexWarning作为异常捕获?在

我尝试过np.seterr,但这没有效果(因为它只与浮点警告有关,如下溢/溢出)。在

我也尝试过标准库中的with warnings.catch_warnings():上下文管理器,但它也没有效果。在


Tags: importnumpy示例binasnparrayusers
1条回答
网友
1楼 · 发布于 2024-10-02 10:18:42

使用stdlib warnings filter会导致这些内容升高而不是打印:

>>> warnings.filterwarnings(action="error", category=np.ComplexWarning)
>>> b = np.array(a, dtype=np.float64)
ComplexWarning: Casting complex values to real discards the imaginary part

您可以使用^{}将其重置为默认筛选器。在

相关问题 更多 >

    热门问题