Pandas python重塑数据帧
我的datafram2中有一排行,看起来像这样。有很多行和两列Pandas python重塑数据帧,pandas,reshape,Pandas,Reshape,我的datafram2中有一排行,看起来像这样。有很多行和两列 player pos Blake Bortles QB Alvin Kamara RB Dion Lewis RB Keenan Allen WR Michael Thomas WR Tyrell Williams WR Hunter Henry TE Stephen Gostkowski K Los Angeles Chargers D Totals Team
player pos
Blake Bortles QB
Alvin Kamara RB
Dion Lewis RB
Keenan Allen WR
Michael Thomas WR
Tyrell Williams WR
Hunter Henry TE
Stephen Gostkowski K
Los Angeles Chargers D
Totals Team 1.0
Blake Bortles QB
Alvin Kamara RB
Dion Lewis RB
Keenan Allen WR
Michael Thomas WR
Tyrell Williams WR
Hunter Henry TE
Stephen Gostkowski K
Jacksonville Jaguars D
Totals Team 2.0
Blake Bortles QB
Todd Gurley RB
Alvin Kamara RB
Michael Thomas WR
Cooper Kupp WR
Tyrell Williams WR
Hunter Henry TE
Stephen Gostkowski K
Los Angeles Chargers D
我正试图重新调整它的形状,以便每11行开始一个新行,并且pos值是列名。所以我希望它看起来像这样:
QB RB RB WR WR WR TE K D team
Blake Bortles Alvin Kamara Dion Lewis Keenan Allen Michael Thomas Tyrell Williams Hunter Henry Stephen Gostkowski Los Angeles Chargers
总分的最后一列1.0并不重要。但我希望第二排成为下一组球员。我试过重塑
如果我删除pos
列并执行以下操作,我已经成功地做到了:
test = pd.DataFrame(rearrange.values.reshape(-1, 10),
columns=['QB','RB','RB','WR','WR','WR','TE','K','D','Team'])
但是我如何使用那里的pos
列呢
有什么想法吗?如果每组的
pos
的顺序和值相同,您需要:
df = pd.DataFrame(df['player'].values.reshape(-1, 10),
columns=df['pos'].iloc[:9].tolist() + ['total'])
print (df)
QB RB RB WR WR \
0 Blake Bortles Alvin Kamara Dion Lewis Keenan Allen Michael Thomas
1 Blake Bortles Alvin Kamara Dion Lewis Keenan Allen Michael Thomas
2 Blake Bortles Todd Gurley Alvin Kamara Michael Thomas Cooper Kupp
WR TE K D \
0 Tyrell Williams Hunter Henry Stephen Gostkowski Los Angeles Chargers
1 Tyrell Williams Hunter Henry Stephen Gostkowski Jacksonville Jaguars
2 Tyrell Williams Hunter Henry Stephen Gostkowski Los Angeles Chargers
total
0 Totals Team
1 Totals Team
2 Totals Team