熊猫转置数据框

时间:2020-10-27 16:27:09

标签: pandas

我有这个df,其中“ Player”是索引:

             Points
Player            
Cássio          0.0
Cássio          0.0
John            0.0
John            2.3

如何实现它的转置:

         1    2   
Cássio  0.0 0.0 
John    0.0 2.3
...

df.T给了我

           0       1      3     4          
Player  Cássio  Cássio   John   John ....
Points        0       0     0   2.3 

但是我需要Player作为索引,并且不会重复很多次。

2 个答案:

答案 0 :(得分:1)

我相信这就是您想要的:

# Turn the index into a column
df.reset_index(inplace=True)
# Declare a column that gives you an inner row id for each player
df['col'] = df.groupby('Player').cumcount()
# Turn your data from long to wide format
df = df.pivot(index='Player', columns='col', values='Points')
# Results looks like this
print(df)

col       0    1
Player          
cassio  0.0  0.0
jon     0.0  2.3

此后,您可能想要再次重置索引并根据需要重命名列。

答案 1 :(得分:0)

让我们再增加一层索引并取消堆栈:

(df.assign(col=df.groupby('Player').cumcount())
   .set_index('col', append=True)
   ['Points'].unstack()
)

输出:

col       0    1    2    3    4
Player                         
Cássio  0.0  0.0  4.7  8.6 -2.1