【问题标题】:Adding a header name to a group of columns in a dataframe in pandas?将标题名称添加到熊猫数据框中的一组列?
【发布时间】:2017-01-30 17:32:29
【问题描述】:

我有如下格式的数据框:

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 下,同时类似地将列 S_1、S_2 和 S_3 合并到标题 Store_S 下,这样输出现在的格式如下所示:

              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

【问题讨论】:

    标签: python pandas dataframe header multiple-columns


    【解决方案1】:

    你可以通过filter过滤concatDataframes

    #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
    

    【讨论】:

    • 非常感谢您的帮助。但是,如果商店数量的值是动态的呢?目前我只提到了两家商店 R 和 S,假设现在我有 15 家这样的商店,我想为它们放置相同类型的标题。
    猜你喜欢
    • 2020-04-27
    • 2016-09-08
    • 1970-01-01
    • 2017-09-29
    • 2018-12-01
    • 1970-01-01
    • 2018-10-14
    • 2021-06-11
    相关资源
    最近更新 更多