熊猫分组链接:将多索引列重命名为一列

时间:2019-04-23 18:19:19

标签: python pandas multi-index

我正在对熊猫数据框进行一些连续操作,需要链接重命名操作。情况是这样的:

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 个答案:

答案 0 :(得分:3)

您可以使用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字符串格式的python 3.6 +。