out = (
df.assign(
rank=df.groupby('TeamID')['Score']
.rank(ascending=False, method='first')
.astype('int')
.astype('str')
)
.pivot(index='TeamID', columns='rank')
.pipe(lambda x: x.set_axis(x.columns.map('_'.join), axis=1))
.sort_index(axis=1, key=lambda x: x.str.split('_').str[1].astype('int'))
.reset_index()
)
出去:
TeamID AthleteID_1 Name_1 Score_1 AthleteID_2 Name_2 Score_2
0 1 2.0 Pete 4.6 4.0 Jim 3.6
1 2 1.0 Bob 4.9 3.0 Steve 4.5
2 3 5.0 Frank 4.2 NaN NaN NaN
示例代码
import pandas as pd
data = {'AthleteID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5},
'TeamID': {0: 2, 1: 1, 2: 2, 3: 1, 4: 3},
'Name': {0: 'Bob', 1: 'Pete', 2: 'Steve', 3: 'Jim', 4: 'Frank'},
'Score': {0: 4.9, 1: 4.6, 2: 4.5, 3: 3.6, 4: 4.2}}
df = pd.DataFrame(data)