我试图在这个简单的表格上做一些修饰,即设置一个 2 级索引,以便 SalePrice 将成为均值和中位数的主要标签,但在下面将分别有均值和中位数。我想要类似以下内容:
SalePrice
LandSlope Mean Median
*data* *data* *data*
我这样做的尝试如下:
#houseprices.info()
sloprice = houseprices[['LandSlope', 'SalePrice']]
sloprice = sloprice.copy()
sloprice_mean = sloprice.groupby(by='LandSlope').mean()
sloprice_mean.rename(columns={'SalePrice': 'Mean'})
sloprice_med = sloprice.groupby(by='LandSlope').median()
sloprice_med.rename(columns={'SalePrice': 'Median'})
sloprice = pd.merge(sloprice_mean, sloprice_med, on='LandSlope')
index = pd.MultiIndex(levels=[['SalePrice'], ['Mean', 'Median']], codes=[[0, 0], [0, 1]])
sloprice.columns.rename(index)
sloprice
我收到的错误信息:
TypeError Traceback (most recent call last)
<ipython-input-34-490152c77e52> in <module>
8 sloprice = pd.merge(sloprice_mean, sloprice_med, on='LandSlope')
9 index = pd.MultiIndex(levels=[['SalePrice'], ['Mean', 'Median']], codes=[[0, 0], [0, 1]])
---> 10 sloprice.columns.rename(index)
11 sloprice
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in rename(self, name, inplace)
1371 TypeError: Must pass list-like as `names`.
1372 """
-> 1373 return self.set_names([name], inplace=inplace)
1374
1375 # --------------------------------------------------------------------
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in set_names(self, names, level, inplace)
1318 else:
1319 idx = self._shallow_copy()
-> 1320 idx._set_names(names, level=level)
1321 if not inplace:
1322 return idx
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in _set_names(self, values, level)
1239 for name in values:
1240 if not is_hashable(name):
-> 1241 raise TypeError(f"{type(self).__name__}.name must be a hashable type")
1242 self._name = values[0]
1243
TypeError: Index.name must be a hashable type
在 Pandas MultiIndex 文档中对代码参数的描述不清楚,这不是可选的,所以我做了一些谷歌搜索以更好地理解 codes
是什么以及它有什么用处,但是我如何'我把它放在语法中似乎是错误的。
如果您能解释我做错了什么以及如何实现我最初想要的效果,我将不胜感激。