player probability_of_win
player1 35%
player2 65%
player3 20%
player4 80%
player5 90%
player6 10%
every 2 rows represent a match of tennis, I want to make a data frame with 1 row per match. like this:
playerA playerB probability_of_win_A probability_of_win_B
player1 player2 35% 65%
player3 player4 20% 80%
player5 player6 90% 10%
CodePudding user response:
Create new columns by integer and modulo 2
in DataFrame.assign
, pass to DataFrame.pivot
with rename
, last flatten MultiIndex in columns
:
df = (df.assign(A = np.arange(len(df.index)) // 2,
B = np.arange(len(df.index)) % 2)
.pivot(index='A', columns='B')
.rename(columns={0:'A', 1:'B'}))
df.columns = df.columns.map(lambda x: f'{x[0]}_{x[1]}')
print (df)
player_A player_B probability_of_win_A probability_of_win_B
A
0 player1 player2 35% 65%
1 player3 player4 20% 80%
2 player5 player6 90% 10%