Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`ValueError: too many values to unpack (expected 4)` with `scipy.stats.linregress`

I know that this error message (ValueError: too many values to unpack (expected 4)) appears when more variables are set to values than a function returns.

scipy.stats.linregress returns 5 values according to the scipy documentation (http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html).

Here is a short, reproducible example of a working call, and then a failed call, to linregress:

What could account for difference and why is the second one poorly called?

from scipy import stats
import numpy as np

if __name__ == '__main__':
    x = np.random.random(10)
    y = np.random.random(10)
    print(x,y)
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)


'''
Code above works
Code below fails
'''

    X = np.asarray([[-15.93675813],
 [-29.15297922],
 [ 36.18954863],
 [ 37.49218733],
 [-48.05882945],
 [ -8.94145794],
 [ 15.30779289],
 [-34.70626581],
 [  1.38915437],
 [-44.38375985],
 [  7.01350208],
 [ 22.76274892]])

    Y = np.asarray( [[  2.13431051],
 [  1.17325668],
 [ 34.35910918],
 [ 36.83795516],
 [  2.80896507],
 [  2.12107248],
 [ 14.71026831],
 [  2.61418439],
 [  3.74017167],
 [  3.73169131],
 [  7.62765885],
 [ 22.7524283 ]])

    print(X,Y) # The array initialization succeeds, if both arrays are print out


    for i in range(1,len(X)):
        slope, intercept, r_value, p_value, std_err = (stats.linregress(X[0:i,:], y = Y[0:i,:]))
like image 327
Muno Avatar asked Aug 02 '16 15:08

Muno


People also ask

How to fix ValueError too many values to unpack in Python?

We get this error when there's a mismatch between the number of variables to the amount of values Python receives from a function, list, or other collection. The most straightforward way of avoiding this error is to consider how many values you need to unpack and then have the correct number of available variables.

How to solve too many values to unpack?

The “valueerror: too many values to unpack (expected 2)” error occurs when you do not unpack all the items in a list. This error is often caused by trying to iterate over the items in a dictionary. To solve this problem, use the items() method to iterate over a dictionary.


1 Answers

Your problem originates from slicing the X and Y arrays. Also you do not need the for loop. Use the following instead and it should work.

slope, intercept, r_value, p_value, std_err = stats.linregress(X[:,0], Y[:,0])
like image 106
Dataman Avatar answered Oct 03 '22 22:10

Dataman