Skip to main content
 首页 » 编程设计

python之使用单独的数据框将多索引映射到现有的 pandas 数据框列

2025年05月04日13kevingrace

我有一个以下格式的现有数据框(我们称它为 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