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

311 views Asked by At

I'm trying to fit a line to my experimental data. When I run the code I usually use I get the error

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)

Here is my code:

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()

Thankful for any kind of help.

1

There are 1 answers

0
Tirth Patel On BEST ANSWER

Please see the documentation page. The function scipy.stats.linregress returns 5 values:

  1. slope
  2. intercept
  3. rvalue
  4. pvalue
  5. stderr

You will need to modify the call to scipy.stats.linregress as follows:

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