pandas - 为什么我在使用 polyfit 函数时得到 "ValueError: data type <class ' numpy.object _'> not inexact."?

标签 pandas numpy matplotlib trendline dtype

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

ValueError: data type <class 'numpy.object_'> not inexact.  
有人可以解释为什么吗?
我的数据框是 Us_corr3;
enter image description here
这是我的代码:
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.

最佳答案

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 数组。首先清理你的数据框!

关于pandas - 为什么我在使用 polyfit 函数时得到 "ValueError: data type <class ' numpy.object _'> not inexact."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62981846/

相关文章:

python - 在 Snow Leopard 上为 Python 编译 Matplotlib

matplotlib - 在 matplotlib 中的图像上绘制网格线

python - 从 Seaborn distplot 获取数据点

Python 3.6 : Creating a pivot table summarizing counts of values for multiple columns in dataframe

python - 如何有效地将数据框中的条目映射到字典

numpy - 使用 numpy 数组迭代多维数组(图像) - python

python - 连接/组合 MX1 numpy 数组与 MXN numpy 数组

python matplotlib 在axes.lines上迭代得到错误的长度

python - 在 python 中如何使用数据透视表输出进行下一步分析?

python - 如何使用我想要的代码对分类列进行编码?