如何为MultiIndex DataFrame的分组底部添加总计行?
为MultiIndex DataFrame按分组添加总计行
原始数据
Count state car status texas civic New 11 undamaged 11 damaged 10 totalled 5 virginia civic New 10 undamaged 20 damaged 10 totalled 5
期望结果
Count state car status texas civic New 11 damaged 10 totalled 5 undamaged 11 total 37 virginia civic New 10 damaged 10 totalled 5 undamaged 20 total 45
尝试代码及报错
尝试用以下代码实现,但触发报错:
s = test.groupby(level=[0,1]).sum() s.index = pd.MultiIndex.from_product([s.index, ['Total']]) df_out = df_full.append(s).sort_index()
报错信息:
NotImplementedError: isna is not defined for MultiIndex
解决方案
方法1:使用groupby+pd.concat
先计算分组总和,调整索引层级后与原数据合并,避免索引不匹配问题:
import pandas as pd # 计算每个(state, car)分组的总和 total_rows = test.groupby(level=[0, 1]).sum() # 为总和行添加第三级索引'total',匹配原索引层级顺序 total_rows.index = total_rows.index.set_levels(['total'], level=2) total_rows.index = total_rows.index.reorder_levels(['state', 'car', 'status']) # 合并原数据与总计行,按索引排序 df_out = pd.concat([test, total_rows]).sort_index(level=[0, 1]) # 若需要和期望结果的status顺序完全一致,可手动指定排序规则 order = ['New', 'damaged', 'totalled', 'undamaged', 'total'] df_out = df_out.reset_index(level=2).loc[lambda x: x['status'].isin(order)].set_index('status', append=True).reorder_levels(['state', 'car', 'status'])
方法2:使用groupby.apply直接追加总计行
通过分组后对每个子DataFrame直接追加总计行,逻辑更直观:
df_out = test.groupby(level=[0, 1], group_keys=False).apply( lambda x: x.append(pd.Series({'Count': x['Count'].sum()}, name=('total'))) ).sort_index(level=[0, 1])
错误原因说明
原代码报错是因为用pd.MultiIndex.from_product构造索引时,导致MultiIndex层级处理逻辑冲突,加上已被pandas弃用的append方法对MultiIndex的兼容性问题,触发了isna未定义的错误。改用pd.concat或groupby.apply可避免这类问题。
内容的提问来源于stack exchange,提问作者Frank R.
相关产品推荐
相关产品推荐

