Python 克服空数组的 ValueError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22903114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:56:45  来源:igfitidea点击:

Overcome ValueError for empty array

pythonnumpymatplotlib

提问by Py-ser

In this discussionI tried to fix a issue in plotting limits for y-axis, after the twiny()messes up my plot. I thought this:

本次讨论中,我试图解决绘制 y 轴限制时的一个问题,在twiny()我的绘图弄乱之后。我是这么想的:

ax.set_ylim([y.min()-0.05, y.max()+0.05])

was a good solution. And probably it is, for continuous set of data. As I said in that discussion, anyway, my data are noisy, and sometimes with gaps. So it happens that some plotted ranges have no data. In that case, naturally, the use of the .min()raises the error:

是一个很好的解决方案。并且可能是,对于连续的数据集。正如我在那次讨论中所说,无论如何,我的数据是嘈杂的,有时还有差距。所以碰巧一些绘制的范围没有数据。在这种情况下,使用 自然.min()会引发错误:

ValueError: zero-size array to reduction operation minimum which has no identity

because the array is empty. How to workaround it, so that the code just does not care of putting limits on the y-axis? (Hoping that this is the only issue the empty array will cause)

因为数组是空的。如何解决它,以便代码不关心在 y 轴上设置限制?(希望这是空数组会导致的唯一问题)

采纳答案by mgilson

Just catch the exception and ignore it:

只需捕获异常并忽略它:

try:
    ax.set_ylim([y.min()-0.05, y.max()+0.05])
except ValueError:  #raised if `y` is empty.
    pass