Python Pandas : Pivot table : aggfunc concatenate instead of np.size or np.sum

后端 未结 1 824
孤城傲影
孤城傲影 2021-01-12 12:14

I have some entries in dataframe like :

name, age, phonenumber
 A,10, Phone1
 A,10,Phone2
 B,21,PhoneB1
 B,21,PhoneB2
 C,23,PhoneC

Here is

1条回答
  •  花落未央
    2021-01-12 12:43

    You can use agg function after the groupby:

    df.groupby(['name', 'age'])['phonenumber'].\
        agg({'phonecount': pd.Series.nunique, 
             'phonenumber': lambda x: ','.join(x)
            }
           )
    
    #               phonenumber  phonecount
    # name  age     
    #    A   10   Phone1,Phone2           2
    #    B   21 PhoneB1,PhoneB2           2
    #    C   23          PhoneC           1
    

    Or a shorter version according to @root and @Jon Clements:

    df.groupby(['name', 'age'])['phonenumber'].\
       agg({'phonecount': 'nunique', 'phonenumber': ','.join})
    

    0 讨论(0)
提交回复
热议问题