将标题名称添加到pandas中的数据框中的一组列?

时间:2017-01-30 17:32:29

标签: python pandas dataframe header multiple-columns

我的数据框格式如下所示:

Product       R_1     R_2      R_3      S_1     S_2      S_3
x            2       4       21        12      43       54
y            5       2       12        42     31       12

现在我想要将R_1,R_2和R_3列分组并在标题Store_R下分配它们,同时将标题Store_S下的列S_1,S_2和S_3组合在一起,这样输出现在的格式如下所示:

              Store_R                Store_S
Product    R_1     R_2      R_3     S_1     S_2       S_3
x         2       4       21      12      43         54
y         5       2       12      42      31         12

1 个答案:

答案 0 :(得分:2)

concat可以filter过滤Dataframes

#if Product is column set to index
df = df.set_index('Product')
print (pd.concat([df.filter(like='R'), 
                  df.filter(like='S')],  
                  axis=1,  
                  keys=('Store_R','Store_S')))

        Store_R         Store_S        
            R_1 R_2 R_3     S_1 S_2 S_3
Product                                
x             2   4  21      12  43  54
y             5   2  12      42  31  12

另一个创建MultiIndex.from_tuples但必须是第一列的解决方案全部是R,然后是S。由于值已分配且可能某些值可能错误对齐。

colsR = [('Store_R', col) for col in df.columns if 'R' in col]
colsS = [('Store_S', col) for col in df.columns if 'S' in col]

df = df.set_index('Product')
df.columns = pd.MultiIndex.from_tuples(colsR + colsS)
print (df)
        Store_R         Store_S        
            R_1 R_2 R_3     S_1 S_2 S_3
Product                                
x             2   4  21      12  43  54
y             5   2  12      42  31  12

sort_index可以帮助对列名进行排序:

print (df)
  Product  S_1  R_2  R_3  S_12  S_2  S_3
0       x    2    4   21    12   43   54
1       y    5    2   12    42   31   12

colsR = [('Store_R', col) for col in df.columns if 'R' in col]
colsS = [('Store_S', col) for col in df.columns if 'S' in col]

df = df.set_index('Product').sort_index(axis=1)
df.columns = pd.MultiIndex.from_tuples(colsR + colsS)
print (df)
        Store_R     Store_S             
            R_2 R_3     S_1 S_12 S_2 S_3
Product                                 
x             4  21       2   12  43  54
y             2  12       5   42  31  12