2016-04-28 10 views
-2
is_correct, question_id 
t   1 
t   1 
f   1 
f   1 
t   2 
t   2 

望ましい結果:どのようにグループ化し、異なる条件に数えますか?

correct_count, incorrect_count, question_id 
2    2    1 
2    0    2 

これは私が持っているものですが、私はあなたがそのためにpivot_table機能を使用することができ、正しい数

df[df["is_correct"]].groupby("question_id")["question_id"].count() 
+0

[python pandas:列内のすべての値に対して条件をグループ化してカウントする方法](http://stackoverflow.com/questions/31458703/python-pandas-how-to-すべての価値のための条件付きのグループごとのカウントn-a-c) –

+0

これは複製です。この質問のためのMaxUの解決策は、他のものよりも良い、より面白い答えを持っています。 – samol

+0

それから、親切に、これの複製として他の質問をマークしてください。 –

答えて

1

を取得することができます:

In [28]: data = """\ 
    ....: is_correct question_id 
    ....: t   1 
    ....: t   1 
    ....: f   1 
    ....: f   1 
    ....: t   2 
    ....: t   2 
    ....: """ 

In [29]: df = pd.read_csv(io.StringIO(data), delim_whitespace=True) 

In [30]: df['count'] = 0 

In [31]: 

In [31]: df 
Out[31]: 
    is_correct question_id count 
0   t   1  0 
1   t   1  0 
2   f   1  0 
3   f   1  0 
4   t   2  0 
5   t   2  0 

In [32]: 

In [32]: df.pivot_table(index='question_id', columns='is_correct', 
    ....:    values='count', aggfunc='count', fill_value=0)\ 
    ....: .reset_index() 
Out[32]: 
is_correct question_id f t 
0      1 2 2 
1      2 0 2 
+0

@samol、それは助けましたか? – MaxU

0

カウントに使用する別の列を作成した後でgroupbyを使用できます。

df = pd.DataFrame({'is_correct':['t','t','f','f','t','t'],'question_id':[1,1,1,1,2,2]}) 
df['to_sum_up']=1 

is_correct question_id to_sum_up 
t   1   1 
t   1   1 
f   1   1 
f   1   1 
t   2   1 
t   2   1 

df2 = df.groupby(['question_id','is_correct'],as_index = False).sum() 

あなたのGROUPBYを作ったら、あなたはそれはあなたがしたい列に合うようにデータを再配置する必要があります。

その後
df2['correct_count'] = df2.ix[df2['is_correct']=='t','N'] 
df2['incorrect_count'] = df2.ix[df2['is_correct']=='f','N'] 

出力として素敵なデータフレームを有するために:

df2.ix[df2['correct_count'].isnull(),'correct_count'] = 0 
df2.ix[df2['incorrect_count'].isnull(),'incorrect_count'] = 0 
df2 = df2.groupby('question_id',as_index = False).max() 
df2 = df2.drop(['N','is_correct'],1) 

     question_id correct_count incorrect_count 
0  1    2    2 
1  2    2    0 
関連する問題