【问题标题】:Why am I getting the "ValueError: data type <class 'numpy.object_'> not inexact." while using polyfit function?为什么我会收到“ValueError:数据类型 <class 'numpy.object_'> 不准确。”在使用 polyfit 函数时?
【发布时间】:2020-11-08 21:43:42
【问题描述】:

我正在尝试为我的数据绘制趋势线。但是,我收到了错误

ValueError: data type <class 'numpy.object_'> not inexact.  

谁能解释一下原因?

我的数据框是 Us_corr3;


这是我的代码:

data5 = Us_corr3[['US GDP', 'US Unemployment']]

x = data5['US GDP']

y = data5['US Unemployment']

plt.scatter(x, y)


z = np.polyfit(x, y, 1)

p = np.poly1d(z)

plt.plot(x,p(x),"r--")

plt.show()

它说;

ValueError: data type <class 'numpy.object_'> not inexact.

【问题讨论】:

  • 给我们更多的信息! data5.dtypes,完整的错误tracebackxSeriesx.to_numpy() 呢? shape, dtype?

标签: pandas numpy matplotlib trendline dtype


【解决方案1】:

如果x,从你的Series派生的数组是object dtype,它会产生你的错误:

In [67]: np.polyfit(np.arange(3).astype(object),np.arange(3),1)                                      
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-67-787351a47e03> in <module>
----> 1 np.polyfit(np.arange(3).astype(object),np.arange(3),1)

<__array_function__ internals> in polyfit(*args, **kwargs)

/usr/local/lib/python3.6/dist-packages/numpy/lib/polynomial.py in polyfit(x, y, deg, rcond, full, w, cov)
    605     # set rcond
    606     if rcond is None:
--> 607         rcond = len(x)*finfo(x.dtype).eps
    608 
    609     # set up least squares equation for powers of x

/usr/local/lib/python3.6/dist-packages/numpy/core/getlimits.py in __new__(cls, dtype)
    380             dtype = newdtype
    381         if not issubclass(dtype, numeric.inexact):
--> 382             raise ValueError("data type %r not inexact" % (dtype))
    383         obj = cls._finfo_cache.get(dtype, None)
    384         if obj is not None:

ValueError: data type <class 'numpy.object_'> not inexact

像这样的函数需要数字 dtype 数组。先清理你的数据框!

【讨论】:

  • 在您回复后,我将数据从对象转换为浮点数。我对 x 和 y 都使用了“x = data5['US GDP'].astype(str).astype(float)”。它奏效了。非常感谢
  • 我的数据被格式化为 Int32 而不是 int - 感谢您的提示。
猜你喜欢
  • 2021-12-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多