简体   繁体   English

Pandas - 数据框架 - 重塑数据框中的值

[英]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

在此输入图像描述

Knowing that games always involve exactly 2 teams, we can manipulate the underlying numpy array. 知道游戏总是涉及2个团队,我们可以操纵底层的numpy数组。

pd.DataFrame(df.values[:, 1:].reshape(-1, 4),
             pd.Index(df.values[::2, 0], name='Game_ID'),
             ['Team', 'Score'] * 2)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM