我有以下格式的现有数据框(我们称其为df):

               A     B     C     D
0              1     2     1     4
1              3     0     2     2
2              1     5     3     1


列名是从具有以下格式的电子表格中提取的(我们称为cat_df):

                      current category
broader category
X                     A
Y                     B
Y                     C
Z                     D


首先,我想添加一个更高级别的索引,使df看起来像这样:

               X     Y           Z
               A     B     C     D
0              1     2     1     4
1              3     0     2     2
2              1     5     3     1


最后,我想通过汇总子索引将数据“汇总”到元索引中,以生成新的数据框,如下所示:

               X     Y     Z
0              1     3     4
1              3     2     2
2              1     8     1


this answer使用concat已经使我接近了,但是似乎要挑选每个子集是一个非常手动的过程。我的真实数据集具有更复杂的映射,因此在构建元索引时我想直接引用它。我认为,一旦我确定了元索引,一个简单的groupby就应该使我掌握总和,但是我仍然停留在第一步。

最佳答案

d = dict(zip(cat_df['current category'], cat_df.index))

cols = pd.MultiIndex.from_arrays([df.columns.map(d.get), df.columns])
df.set_axis(cols, axis=1, inplace=False)

   X  Y     Z
   A  B  C  D
0  1  2  1  4
1  3  0  2  2
2  1  5  3  1




df_new = df.set_axis(cols, axis=1, inplace=False)
df_new.groupby(axis=1, level=0).sum()

   X  Y  Z
0  1  3  4
1  3  2  2
2  1  8  1

10-08 07:54
查看更多