我在数据框中有一些条目,例如:
name, age, phonenumber
A,10, Phone1
A,10,Phone2
B,21,PhoneB1
B,21,PhoneB2
C,23,PhoneC
这是我试图通过数据透视表实现的结果:
name, age, phonenumbers, phonenocount
A,10, "Phone1,Phone2" , 2
B,21, "PhoneB1,PhoneB2", 2
C,23, "PhoneC" , 1
我正在尝试类似的东西:
pd.pivot_table(phonedf, index=['name','age','phonenumbers'], values=['phonenumbers'], aggfunc=np.size)
但是我希望将电话号码连接起来作为 aggfunc 的一部分。 有什么建议吗?
最佳答案
你可以在groupby
之后使用agg
函数:
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
或根据@root 和@Jon Clements 的更短版本:
df.groupby(['name', 'age'])['phonenumber'].\
agg({'phonecount': 'nunique', 'phonenumber': ','.join})
关于Python Pandas : Pivot table : aggfunc concatenate instead of np. 大小或 np.sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38981885/