本文介绍了Python:ValueError:值太多,无法从Excel解包(应为2)数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从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(),您将收到

这篇关于Python:ValueError:值太多,无法从Excel解包(应为2)数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 06:59