我有一个表示玩家,团队和胜利的DataFrame。我想要做的是创建一个新的DataFrame,其中team是索引,是否代表了该团队中的玩家x,以及该团队是否获胜。
pd.DataFrame(data=[['Team A', 1], ['Team B', 0], ['Team B', 0], ['Team A', 1]], columns=['TEAM', 'WIN'], index=['Player 1', 'Player 2', 'Player 3', 'Player 4'])
TEAM WIN
Player 1 Team A 1
Player 2 Team B 0
Player 3 Team B 0
Player 4 Team A 1
期望的结果:
pd.DataFrame(data=[[1, 1, 0, 0, 1], [0, 0, 1, 1, 0]], columns=['Player 1', 'Player 2', 'Player 3', 'Player 4', 'WIN'], index=['Team A', 'Team B'])
Player 1 Player 2 Player 3 Player 4 WIN
Team A 1 1 0 0 1
Team B 0 0 1 1 0
答案 0 :(得分:2)
IIUC您可以使用pivot_table()
方法:
In [96]: df.reset_index().pivot_table(index='TEAM', columns='index', values='WIN', fill_value=0)
Out[96]:
index Player 1 Player 2 Player 3 Player 4
TEAM
Team A 1 0 0 1
Team B 0 0 0 0