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

1 Answer

When you're getting an error from your code, it would help to pose 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest