2017-05-30 165 views
5

我的目標很簡單,但不確定是否有可能。重複的例子:熊貓:Groupby創建計數和計數值表

你能從這個去:

raw_data = {'score': [1, 3, 4, 4, 1, 2, 2, 4, 4, 2], 
     'player': ['Miller', 'Jacobson', 'Ali', 'George', 'Cooze', 'Wilkinson', 'Lewis', 'Lewis', 'Lewis', 'Jacobson']} 
df = pd.DataFrame(raw_data, columns = ['score', 'player']) 
df 

    score player 
0 1  Miller 
1 3  Jacobson 
2 4  Ali 
3 4  George 
4 1  Cooze 
5 2  Wilkinson 
6 2  Lewis 
7 4  Lewis 
8 4  Lewis 
9 2  Jacobson 

要這樣:

 score col_1  col_2  col_3  col_4  
score 
1  2  Miller  Cooze  n/a   n/a 
2  3  Wilkinson Lewis  Jacobson n/a 
3  1  Jacobson n/a   n/a   n/a 
4  4  Ali   George  Lewis  Lewis 

通過一個groupby

我可以得到這個遠df.groupby(['score']).agg({'score': np.size}),但不能解決如何創建具有列值的新列。

回答

6

我可以

選項1

g = df.groupby('score').player 
g.size().to_frame('score').join(g.apply(list).apply(pd.Series).add_prefix('col_')) 

     score  col_0 col_1  col_2 col_3 
score           
1   2  Miller Cooze  NaN NaN 
2   3 Wilkinson Lewis Jacobson NaN 
3   1 Jacobson  NaN  NaN NaN 
4   4  Ali George  Lewis Lewis 

選項2

d1 = df.groupby('score').agg({'score': 'size', 'player': lambda x: tuple(x)}) 
d1.join(pd.DataFrame(d1.pop('player').values.tolist()).add_prefix('col_')) 

     score  col_0 col_1  col_2 col_3 
score           
1   2  Miller Cooze  NaN NaN 
2   3 Wilkinson Lewis Jacobson NaN 
3   1 Jacobson  NaN  NaN NaN 
4   4  Ali George  Lewis Lewis 
+2

@MaxU我用'pop'複製你的輸出!我爲自己感到自豪:-) – piRSquared

+0

兩者都很華麗。我沒有得到選項2的正確輸出(可能是因爲我使用Python 3?)。儘管如此,選項1是完美的。 – RDJ