[英]Pandas: how to make pivot table with new columns?
I have a table from several files with the same names, but different values:我有一个来自多个具有相同名称但值不同的文件的表:
I need to make new columns, based on the number of repeating names with the saved number of participants, so it looks like this:我需要根据重复姓名的数量和保存的参与者数量创建新列,因此它看起来像这样:
I tried to make the pivot table without division of points using我试图制作数据透视表而不使用
df.pivot(index='Name', columns='numbers of participants')
But I got an error.但我有一个错误。
Is it possible to make new columns using the pivot table function?是否可以使用数据透视表功能创建新列?
Use GroupBy.cumcount
for counter and pass to DataFrame.pivot
with DataFrame.add_prefix
:使用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.