Python:ValueError:值太多,无法从Excel解包(应为2)数据

2022-02-26 00:00:00 python pandas gaussian kernel

问题描述

我想从excel中获取数据,并用python绘制2D内核密度估计,但它显示";ValueError:Too More Value to Unpack(Expect 2)&Quot;。怎么修呢?以下是编码:

# libraries
import matplotlib.pyplot as plt
from scipy.stats import kde
import pandas as pd
 
# create data
x = pd.read_excel(r'C:UsersEzraDesktopmontex.xlsx')
y = pd.read_excel(r'C:UsersEzraDesktopmontey.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()

解决方案

当您从代码中收到错误时,设置实际的回溯会很有帮助,尤其是指示示例代码的哪一行导致错误的部分。

调用返回多个值的函数时,可以将其解包为单独的变量。ValueError: too many values to unpack (expected 2)表示您调用了仅返回单个值的函数,但您尝试将返回值解包为两个变量。

例如,考虑这个小python脚本:

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

运行时:

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

更一般的错误消息使其更加清晰。例如,如果您尝试调用x,y,z = return_2_vals(),您将收到

ValueError:没有足够的值来解包(预期为%3,实际为%2)

相关文章