我通过提供 2 列作为数据透视输入,从数据框中创建数据透视表,如下面的代码所示。应用枢轴后,我需要使用此堆叠输出与类似的列数据框合并,因为我想丢弃也出现在索引名称上方的名称(“品牌和类型”),我该如何实现这一点。请注意我想保留堆叠输出import pandas as pdcars = {'day':['aug','aug','sep','sep','aug'], 'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4','Hyundai Elite i20'], 'Type':['sedan,','sedan','hatchback','hatchback','hatchback'], 'Down Price': [22000,25000,27000,35000,10000] }df = pd.DataFrame(cars, columns = ['day','Brand', 'Type','Down Price'])dfpivot=pd.pivot_table(df,index=['day'],columns=['Brand','Type'],values=['Down Price'],aggfunc=np.max)dfpivot.columns = dfpivot.columns.droplevel(0)我尝试重置索引但没有成功dfpivot.rename_axis(None, axis=1).reset_index()然后我尝试删除索引,但这也不起作用。如何删除出现在索引上方的名称、品牌和类型。先感谢您。添加溶液后dfpivot.columns.name=[None,None]追溯:---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-102-ef1eb88ee6b2> in <module> 10 dfpivot=pd.pivot_table(df,index=['day'],columns=['Brand','Type'],values=['Down Price'],aggfunc=np.max) 11 ---> 12 dfpivot.columns.name=[None,None]~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in name(self, value) 1192 "'MultiIndex.set_names' instead." 1193 )-> 1194 maybe_extract_name(value, None, type(self)) 1195 self._name = value 1196 ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in maybe_extract_name(name, obj, cls) 5402 # GH#29069 5403 if not is_hashable(name):-> 5404 raise TypeError(f"{cls.__name__}.name must be a hashable type") 5405 5406 return nameTypeError: MultiIndex.name must be a hashable type
1 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
这些就是专栏names
。只需将它们设置为None
:
dfpivot.columns.names = [None, None] dfpivot.index.names = [None] # only do this if you do not want the name of your index (day)
添加回答
举报
0/150
提交
取消