[英]Pandas: how to make pivot table with new columns?
使用GroupBy.cumcount
計數器和傳球DataFrame.pivot
與DataFrame.add_prefix
:
df['g'] = df.groupby(['Name', 'numbers of participants']).cumcount().add(1)
df1 = (df.pivot(index=['Name','numbers of participants'], columns='g', values='points')
.add_prefix('points_')
.reset_index()
.rename_axis(None, axis=1))
print (df1)
Name numbers of participants points_1 points_2
0 A 20 7679 124
1 B 30 23 231
2 C 40 341 4124
df1['numbers of participants'] = df1.pop('numbers of participants')
print (df1)
Name points_1 points_2 numbers of participants
0 A 7679 124 20
1 B 23 231 30
2 C 341 4124 40
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.