首页 > 解决方案 > 根据对 Dataframe 的查找将列替换为多级列

问题描述

如何替换此单列标题:

    foo bar
0   0   0
1   0   0

要获得这些多级列:

    A   B
    a   b
0   0   0
1   0   0

基于此数据帧映射

    col1    col2    col3
0   foo     a       A
1   bar     b       B
2   baz     c       C

我正在尝试一个列表理解,试图创建一个新的多级列索引,但似乎没有工作......我觉得有一种更 Python 的方式来实现这一点

df1 = pd.DataFrame({'foo':[0,0],
                    'bar':[0,0]})
df2 = pd.DataFrame({'col1':['foo','bar','baz'],
                    'col2':['A','B','C'],
                    'col3':['a','b','c']})

df1.columns = [(df2.loc[df2['col1']==i,'col2'], df2.loc[df2['col1']==i,'col3']) for i in df1.columns]

标签: pythonpandashierarchical-data

解决方案


您可以将 df2 转换为一系列元组并将其映射到列:

df1.columns = df1.columns.map(df2.set_index('col1').apply(tuple, axis=1))

输出:

   A  B
   a  b
0  0  0
1  0  0

推荐阅读