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
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.