reset_index() 不适用于多索引数据帧 - 'cannot insert an item into a CategoricalIndex that is not already an existing category'
reset_index() not working for multiindex dataframe - 'cannot insert an item into a CategoricalIndex that is not already an existing category'
我正在使用此代码获取此数据框:
df=df[['rank','Grade','search']].groupby(['Grade','rank']).count()
df2=df.div(df.groupby(['Grade']).transform('sum'))
df3=df2.unstack()
| search |
| rank | 1 | 2 | 3 | 4 | 5 | 5-10 | 10-20 | 20+ |
| Grade ---|-----|-----|-----|-----|-----|------|-------|-----|
| A | 0.2 | 0.2 | 0.2 | 0.1 | 0.04| 0.04 | 0.01 | NaN |
| B | 0.3 | 0.2 | 0.1 | 0.2 | 0.03| 0.05 | 0.2 | NaN |
现在,要为 Grade
绘制条形图,我通常会在未堆叠的 table 上绘制 reset_index()
。但是,如果我现在这样做,我会收到此错误:
TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
我已经尝试了各种方法,但我无法修复它。这很奇怪,因为它适用于另一个 table,格式完全相同,只是相反(即先按等级分组,然后按等级分组)
您可以将分类转换为字符串:
df3 = df_grade2.unstack().rename(columns=str).reset_index()
我正在使用此代码获取此数据框:
df=df[['rank','Grade','search']].groupby(['Grade','rank']).count()
df2=df.div(df.groupby(['Grade']).transform('sum'))
df3=df2.unstack()
| search |
| rank | 1 | 2 | 3 | 4 | 5 | 5-10 | 10-20 | 20+ |
| Grade ---|-----|-----|-----|-----|-----|------|-------|-----|
| A | 0.2 | 0.2 | 0.2 | 0.1 | 0.04| 0.04 | 0.01 | NaN |
| B | 0.3 | 0.2 | 0.1 | 0.2 | 0.03| 0.05 | 0.2 | NaN |
现在,要为 Grade
绘制条形图,我通常会在未堆叠的 table 上绘制 reset_index()
。但是,如果我现在这样做,我会收到此错误:
TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category
我已经尝试了各种方法,但我无法修复它。这很奇怪,因为它适用于另一个 table,格式完全相同,只是相反(即先按等级分组,然后按等级分组)
您可以将分类转换为字符串:
df3 = df_grade2.unstack().rename(columns=str).reset_index()