Python 3.8
我对Python相当陌生,我需要在20/12/11星期五之前完成此项目。我有一个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
和values
长度不相等。使用两个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的评论:
#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())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句