【问题标题】:Python DataFrame - ValueError: too many values to unpack (expected 2)Python DataFrame - ValueError:解包的值太多(预期 2)
【发布时间】:2020-12-05 11:36:37
【问题描述】:

Python 3.8

我是 Python 的新手,我需要在 2020 年 11 月 12 日星期五之前交付这个项目。 我有一个 DataFrame,我必须打印 name_list 中保存的列的“价格”键的平均值和标准差。

这是我写的代码:

#Grouping by company, fuel type, aspiration, door number
#Creating an empty DataFrame
result = pd.DataFrame()
#Saving all the prices
values = df['price'].unique()
name_list = ['CarName', 'fueltype', 'aspiration', 'doornumber']
#Cycling for each column and saving the mean and standard deviation in the empty dataframe
for name, value in name_list, values:
    result["Mean Price = ", value] = df[df.price == value][name].mean()
    result["Standard Deviation = ", value] = df[df.price == value][name].std()

#result = result.dropna()

#Saving mean price and standard deviation to a csv file
result.to_csv("MeanPrice_StdDeviation.csv", index=False)

当我运行代码时,我得到了错误: ValueError:要解压的值太多(预期为 2)

我在网上读到你可以使用 items 方法,但是如果我尝试这样做,它就不起作用,因为我得到这个错误: AttributeError:“numpy.ndarray”对象没有属性“items”

我该如何解决这个问题?

编辑: 这是我尝试嵌套 for 循环时收到的完整错误消息。 我这部分代码的行数从 38 到 53。

Traceback (most recent call last):

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1303, in _ensure_numeric
    x = float(x)

ValueError: could not convert string to float: 'alfa-romero giulia'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1307, in _ensure_numeric
    x = complex(x)

ValueError: complex() arg is a malformed string


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "c:\users\mazza\documents\informatica\progetto_esame_peruzzini_mazzanti.py", line 48, in <module>
    result["Mean Price = ", value] = df[df.price == value][name].mean()

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\generic.py", line 11214, in stat_func
    return self._reduce(

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\series.py", line 3891, in _reduce
    return op(delegate, skipna=skipna, **kwds)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 69, in _f
    return f(*args, **kwargs)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 125, in f
    result = alt(values, axis=axis, skipna=skipna, **kwds)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 542, in nanmean
    the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1310, in _ensure_numeric
    raise TypeError(f"Could not convert {x} to numeric")

TypeError: Could not convert alfa-romero giulia to numeric


debugfile('C:/Users/mazza/Documents/Informatica/progetto_esame_peruzzini_mazzanti.py', wdir='C:/Users/mazza/Documents/Informatica')

Traceback (most recent call last):

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1303, in _ensure_numeric
    x = float(x)

ValueError: could not convert string to float: 'alfa-romero giulia'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1307, in _ensure_numeric
    x = complex(x)

ValueError: complex() arg is a malformed string


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "c:\users\mazza\documents\informatica\progetto_esame_peruzzini_mazzanti.py", line 47, in <module>
    result["Mean Price = ", value] = df[df.price == value][name].mean()

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\generic.py", line 11214, in stat_func
    return self._reduce(

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\series.py", line 3891, in _reduce
    return op(delegate, skipna=skipna, **kwds)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 69, in _f
    return f(*args, **kwargs)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 125, in f
    result = alt(values, axis=axis, skipna=skipna, **kwds)

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 542, in nanmean
    the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum))

  File "C:\Users\mazza\anaconda3\lib\site-packages\pandas\core\nanops.py", line 1310, in _ensure_numeric
    raise TypeError(f"Could not convert {x} to numeric")

TypeError: Could not convert alfa-romero giulia to numeric

【问题讨论】:

  • 这是因为您的 name_list 长度和循环中的值不匹配。如果列表/数组的长度不匹配,请尝试使用嵌套 for 循环。

标签: python-3.x pandas dataframe


【解决方案1】:

您遇到此问题是因为 name_listvalues 的长度不等。使用两个 for 循环(嵌套)尝试以下代码:

#Grouping by company, fuel type, aspiration, door number
#Creating an empty DataFrame
result = pd.DataFrame()
#Saving all the prices
values = df['price'].unique()
name_list = ['CarName', 'fueltype', 'aspiration', 'doornumber']
#Cycling for each column and saving the mean and standard deviation in the empty dataframe   
for name in name_list:
    for value in values:
        result["Mean Price = ", value] = df[df.price == value][name].mean()
        result["Standard Deviation = ", value] = df[df.price == value][name].std()

#result = result.dropna()

#Saving mean price and standard deviation to a csv file
result.to_csv("MeanPrice_StdDeviation.csv", index=False)

编辑以下 OP 的 cmets:

#Grouping by company, fuel type, aspiration, door number
#Creating an empty DataFrame
result = pd.DataFrame()
#Saving all the prices
values = df['price'].unique()
name_list = ['CarName', 'fueltype', 'aspiration', 'doornumber']
#Cycling for each column and saving the mean and standard deviation in the empty dataframe   
for column in name_list:    
    print(df.groupby([column])['price'].mean().reset_index())
    print(df.groupby([column])['price'].std().reset_index())

【讨论】:

  • @Mazza 哪个错误?请将其粘贴到 cmets 中。
  • TypeError: 无法将 alfa-romero giulia 转换为数字
  • @Mazza 这意味着代码需要一个数值而不是字符串alfa-romeo。您在哪一行收到此错误?
  • 尝试调试,它发生在第一次迭代:result["Mean Price = ", value] = df[df.price == value][name].mean()
  • @Mazza 好的,现在我明白你的问题了,获取平均值的逻辑是错误的,因为 [name] 是一个非数字值。我已经通过对提到的每一列进行分组来更新答案以获得平均值和标准差。如果这能解决您的问题,请将答案标记为正确。
猜你喜欢
  • 2016-05-24
  • 1970-01-01
  • 2021-07-05
  • 2017-08-29
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2017-12-14
相关资源
最近更新 更多