Scipy.stats 尝试对 .csv 数据集进行 linregress 时出现错误 "Too many values to unpack"

Scipy.stats error "Too many values to unpack" when attempting linregress on .csv dataset

我正在尝试用我的实验数据拟合一条直线。当我 运行 我通常使用的代码时,我得到错误

Traceback (most recent call last): File "/home/h/oscillator1.py", line 21, in slope, intercept, r_value = scipy.stats.linregress(data) ValueError: too many values to unpack (expected 3)

这是我的代码:

import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 
import scipy.stats


data = pd.read_csv("/home/h/Documents/oscillator1.csv", decimal='.')

plt.plot(
         data['t (s)'], data['x (cm)'],
         marker='+',
         linestyle="None",
         label="Data"
         )

plt.xlabel("t [s]", fontsize=13) 
plt.ylabel("x [cm]", fontsize=13) 
plt.xticks(np.arange(0, 1300, step=150), size = 13) 
plt.yticks(np.arange(-11, 2, step=1), size = 13) 
plt.title("x vs t from torsion balance measurements", fontsize=16)

slope, intercept, r_value = scipy.stats.linregress(data) 
print("slope = {}, intercept = {} and r-value = {}".format(slope, intercept, r_value**2))

plt.plot(data['t (s)'],
         data['t (s)']*slope+intercept,
         label="Linear regression"
         )

plt.legend(fontsize=12) plt.show()

感谢任何形式的帮助。

请参阅documentation page。函数scipy.stats.linregress returns 5个值:

  1. 坡度
  2. 拦截
  3. 右值
  4. p值
  5. 标准错误

您需要修改对 scipy.stats.linregress 的调用,如下所示:

slope, intercept, r_value, p_value, stderr = scipy.stats.linregress(data)