Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: ValueError: too many values to unpack (expected 2) data from excell

I want to take data from excel and plot 2D kernel density estimate in python, but it says "ValueError: too many values to unpack (expected 2)". how to fix it? following the coding:

# libraries
import matplotlib.pyplot as plt
from scipy.stats import kde
import pandas as pd
 
# create data
x = pd.read_excel(r'C:\Users\Ezra\Desktop\montex.xlsx')
y = pd.read_excel(r'C:\Users\Ezra\Desktop\montey.xlsx')
 
# Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
nbins=500
k = kde.gaussian_kde([x,y])
xi, yi = pd.mgrid[x.min():x.max():nbins*100j, y.min():y.max():nbins*100j]
zi = k(pd.vstack([xi.flatten(), yi.flatten()]))
 
# Make the plot
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto')
plt.show()
 
# Change color palette
plt.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='auto', cmap=plt.cm.Greens_r)
plt.show()
like image 350
EZF Avatar asked Dec 06 '25 08:12

EZF


2 Answers

When you're getting an error from your code, it would help to post the actual traceback, especially the part that indicates which line of your sample code is causing the error.

When you call a function that returns multiple values, you can "unpack" it into individual variables. ValueError: too many values to unpack (expected 2) means that you called a function that only returns a single value, but you tried to unpack the return value into two variables.

For example, consider this little python script:

def returns_1_val(): 
    return 'one'

def returns_2_vals(): 
    return 'one', 'two'

print(returns_2_vals())

# Unpack the return value.
x,y = returns_2_vals()
print('x', x)
print('y', y)

print(returns_1_val())

# This next call fails.  We're "expecting" Python to unpack 2 values into 
# x and y, but it fails because the function only returned one value.   
x,y = returns_1_val()

When you run it:

('one', 'two')
x one
y two
one
Traceback (most recent call last):
  File "unpack_err.py", line 11, in <module>
    x,y = returns_1_val()
ValueError: too many values to unpack (expected 2)

The more general error message makes it a little more clear. For example, if you try to call x,y,z = return_2_vals(), you'll get

ValueError: not enough values to unpack (expected 3, got 2)

like image 64
Tom Bryan Avatar answered Dec 08 '25 22:12

Tom Bryan


I dont think the answer of Tom Bryan is correct. Your error says: ""ValueError: too many values to unpack (expected 2)" which is the opposite example given by Tom.

Tom says "ValueError: too many values to unpack (expected 2) means that you called a function that only returns a single value". I think this is wrong, what it means is that you called a function that returns more than 2 values. Your function is probably trying to assign more than 2 values to only 2 variables.

like image 42
André Rodrigues Pereira Avatar answered Dec 08 '25 21:12

André Rodrigues Pereira