[英]Pandas - Data Frame - Reshaping Values in Data Frame
I am new to Pandas and have a data frame with a team's score in 2 separate columns. 我是Pandas的新手,并且拥有一个数据框,其中包含2个独立列中的团队成绩。 This is what I have.
这就是我所拥有的。
Game_ID Teams Score
1 Team A 95
1 Team B 85
2 Team C 90
2 Team D 72
This is where I would like to get to and then ideally to. 这是我想去的地方,然后理想的去。
1 Team A 95 Team B 94
2 Team C 90 Team B 72
You can try something as follows: Create a row_id
within each group by the Game_ID
and then unstack by the row_id
which will transform your data to wide format: 你可以试一下如下:创建一个
row_id
在各组内Game_ID
然后拆散row_id
这将改变你的数据,以宽幅:
import pandas as pd
df['row_id'] = df.groupby('Game_ID').Game_ID.transform(lambda g: pd.Series(range(g.size)))
df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1)
Update : 更新 :
If the row_id
is preferred to be dropped, you can drop the level from the columns: 如果首选删除
row_id
则可以从列中删除级别:
df1 = df.set_index(['row_id', 'Game_ID']).unstack(level=0).sortlevel(level = 1, axis = 1)
df1.columns = df1.columns.droplevel(level = 1)
df1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.