TypeError:%d格式需要一个数字,而不是numpy.float64

4 投票
2 回答
13008 浏览
提问于 2025-04-18 01:51

我在尝试绘图时,遇到了来自 matplotlib 的错误:

TypeError: %d format: a number is required, not numpy.float64

这是完整的错误追踪信息(我修改了路径名):

Traceback (most recent call last):
  File ".../plotmod.py", line 154, in _plot
    fig.autofmt_xdate()
  File ".../local/lib/python2.7/site-packages/matplotlib/figure.py", line 426, in autofmt_xdate
    for label in ax.get_xticklabels():
  File ".../local/lib/python2.7/site-packages/matplotlib/axes.py", line 2620, in get_xticklabels
    self.xaxis.get_ticklabels(minor=minor))
  File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1118, in get_ticklabels
    return self.get_majorticklabels()
  File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1102, in get_majorticklabels
    ticks = self.get_major_ticks()
  File ".../local/lib/python2.7/site-packages/matplotlib/axis.py", line 1201, in get_major_ticks
    numticks = len(self.get_major_locator()())
  File ".../local/lib/python2.7/site-packages/matplotlib/dates.py", line 595, in __call__
    'RRuleLocator estimated to generate %d ticks from %s to %s: exceeds Locator.MAXTICKS * 2 (%d) ' % (estimate, dmin, dmax, self.MAXTICKS * 2))
TypeError: %d format: a number is required, not numpy.float64

这个错误是怎么来的呢?

我做了一些基础的研究,得到了以下结果:

  • 这个错误并不是实际的错误,而是在尝试格式化 matplotlib.dates 抛出的 RuntimeError 消息时产生的。
  • 格式化错误是因为 Python 的 %d,似乎无法处理 numpy.float64 类型的数据。
  • 包含这种数据类型的实例可能是 estimate,这是 matplotlib 内部计算的结果,或者是 MAXTICKS,这可能是一个常量,所以我倾向于认为是第一个选项。
  • estimate 的计算涉及到 date2num,它应该返回合法的值,还有 _get_unit()_get_interval(),这些函数深入到模块内部,而我的研究在这里停止了。

我可以在整个软件框架中轻松重现这个错误,但我无法隔离出简单的重现代码。我觉得这个错误往往发生在应该绘制的整个坐标轴非常短的时候(比如说,只有几分钟长)。

有什么想法吗?

2 个回答

0

手动将numpy的浮点数转换为Python的浮点数。

np.asscalar(np.float64(42)) 
4

看起来你遇到了一个问题,就是你试图把一个“不是数字”(NaN)或无穷大(infinity)格式化成整数,这样会导致错误(因为整数类型是不能有NaN或无穷大的)。

In [1]: import numpy as np

In [2]: '%d' % np.float64(42)
Out[2]: '42'

In [3]: '%d' % np.float64('nan')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython console> in <module>()

TypeError: %d format: a number is required, not numpy.float64

In [4]: '%d' % np.float64('inf')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

ipython console> in <module>()

TypeError: %d format: a number is required, not numpy.float64

你可以去修改生成错误的matplotlib文件(或者使用Python调试工具),把打印的那一行改成使用 %f,这样就可以处理所有的numpy浮点数了。(比如 '%f' % np.float64('nan') 会返回 'nan')。

撰写回答