2017-05-30 3 views
5

私の目的は簡単ですが、可能かどうかはわかりません。再現性の例:groupby経由パンダ:カウントとカウント値を持つテーブルを作成するGroupby

 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 

:これに

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 

あなたはここから行くことができますか?

私はこれまでのところ、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私は `pop`を使用@MaxU

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

であなたの出力を複製することができます!私は自分自身を誇りに思っています:-) – piRSquared

+0

どちらも豪華です。私はオプション2のための正しい出力を得ていない(おそらく私はPython 3を使用しているから?)。それにもかかわらず、オプション1は完璧です。 – RDJ

関連する問題