player probability_of_win
player1 35%
player2 65%
player3 20%
player4 80%
player5 90%
player6 10%
每2行代表一场网球比赛,我想创建一个每一场比赛1行的数据帧。这样的:
playerA playerB probability_of_win_A probability_of_win_B
player1 player2 35% 65%
player3 player4 20% 80%
player5 player6 90% 10%
在DataFrame.assign
中对2
进行整模创建新列,用rename
传递给DataFrame.pivot
,最后平展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%