[英]pandas group by and convert rows into multiple columns
data = {'groupId':[1,1,2], 'email':['a1@gmail.com', 'a2@gmail.com', 'a3@gmail.com'],
'type':['office','personal','personal'],'name':['santy','santy','will']}
df = pd.DataFrame(data)
我有一个像这样的 dataframe
groupId email type name
1 a1@gmail.com office santy
1 a2@gmail.com personal santy
2 a3@gmail.com personal will
我想根据特定组中的行数将行转换为动态列
groupId email1 type1 email2 type2 name
1 a1@gmail.com office a2@gmail.com personal santy
2 a3@gmail.com personal na na will
我知道我可以将 set_index 与 unstack 一起使用,但对如何给出列名并在特定组中创建那么多列感到困惑。
有没有有效的方法来做到这一点? 任何帮助,将不胜感激
你可以做:
new_df = (df.assign(col=df.groupby('groupId').cumcount()+1)
.set_index(['groupId','col'])
.unstack('col')
.sort_index(level=(1,0), axis=1)
)
new_df.columns = [f'{x}{y}' for x,y in new_df.columns]
Output:
email1 type1 email2 type2
groupId
1 a1@gmail.com office a2@gmail.com personal
2 a3@gmail.com personal NaN NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.