代码之家  ›  专栏  ›  技术社区  ›  astro123

按链接分组:将多索引列重命名为一行列

  •  1
  • astro123  · 技术社区  · 7 年前

    我在pandas数据帧上做了一些连续的操作,我需要链接重命名操作。情况是这样的:

    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    df = sns.load_dataset('tips')
    
    g = (df.groupby(['sex','time','smoker'])
         .agg({'tip': ['count','sum'],
               'total_bill': ['count','mean']})
         .reset_index()
        )
    
    print(g.head())
    

    这将提供:

          sex    time smoker   tip         total_bill           
                             count     sum      count       mean
    0    Male   Lunch    Yes    13   36.28         13  17.374615
    1    Male   Lunch     No    20   58.83         20  18.486500
    2    Male  Dinner    Yes    47  146.79         47  23.642553
    3    Male  Dinner     No    77  243.17         77  20.130130
    4  Female   Lunch    Yes    10   28.91         10  17.431000
    

    没有链锁

    g.columns = [i[0] + '_' + i[1] if i[1] else i[0] 
                 for i in g.columns.ravel()]
    

    它工作得很好,但是我想链接这个重命名列的过程,这样我就可以链接其他的操作了。

    但我想要内环

    怎么做?

    所需输出 :

    g = (df.groupby(['sex','time','smoker'])
         .agg({'tip': ['count','sum'],
               'total_bill': ['count','mean']})
         .reset_index()
         .rename(something here)
         # or .set_axis(something here)
         # or, .pipe(something here)  I am not sure.
        ) # If i could do this this, i can do further chaining
    
         sex    time     smoker tip_count tip_sum  total_bill_count total_bill_mean
    0    Male   Lunch    Yes    13   36.28         13  17.374615
    1    Male   Lunch     No    20   58.83         20  18.486500
    2    Male  Dinner    Yes    47  146.79         47  23.642553
    3    Male  Dinner     No    77  243.17         77  20.130130
    4  Female   Lunch    Yes    10   28.91         10  17.431000
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Scott Boston    7 年前

    你可以用 pipe 要处理此问题:

    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    df = sns.load_dataset('tips')
    
    g = (df.groupby(['sex','time','smoker'])
         .agg({'tip': ['count','sum'],
               'total_bill': ['count','mean']})
         .reset_index()
         .pipe(lambda x: x.set_axis([f'{a}_{b}' if b == '' else f'{a}' for a,b in x.columns], axis=1, inplace=False))
        )
    
    print(g.head())
    

          sex    time smoker  tip_count  tip_sum  total_bill_count  total_bill_mean
    0    Male   Lunch    Yes         13    36.28                13        17.374615
    1    Male   Lunch     No         20    58.83                20        18.486500
    2    Male  Dinner    Yes         47   146.79                47        23.642553
    3    Male  Dinner     No         77   243.17                77        20.130130
    4  Female   Lunch    Yes         10    28.91                10        17.431000
    

    注意:我使用的是f字符串格式,python3.6+是必需的。