How to groupby with certain condition in pandas dataframe
<p>I have dataframe like this</p>

<pre><code>    A   B
0   1   a
1   2   a
2   3   b
3   4   b
4   5   a
</code></pre>

<p>I want to get result below(1row*4column dataframe),</p>

<pre><code>A_count_all means the number of rows in dataframe   df.A.count()

A_sum_all means the df.A.sum()

A_count_a is df.loc[df.B==a,"A"].count()

A_sum_a is df.loc[df.B==a,"A"].sum()


    A_count_all   A_sum_all  A_count_a   A_sum_a  
0      5            15          3            8
</code></pre>

<p>how can I get this result dataframe?</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor:</p>

<pre><code>A_count_all = df.A.count()
A_sum_all = df.A.sum()
A_count_a = df.loc[df.B=='a',"A"].count()
A_sum_a = df.loc[df.B=='a',"A"].sum()

print (pd.DataFrame({'A_count_all':A_count_all, 
                     'A_sum_all':A_sum_all,
                     'A_count_a':A_count_a,
                     'A_sum_a':A_sum_a},
                      index=[0],
                      columns=['A_count_all','A_sum_all','A_count_a','A_sum_a']))

   A_count_all  A_sum_all  A_count_a  A_sum_a
0            5         15          3        8
</code></pre>

<p>Thank you <a href="http://stackoverflow.com/questions/39332665/how-to-groupby-with-certain-condition-in-pandas-dataframe/39332727?noredirect=1#comment65997064_39332727"><code>Kris</code></a> for another solution:</p>

<pre><code>print (pd.DataFrame(data=[[df.A.count(),
                          df.A.sum(),
                          df.loc[df.B=='a',"A"].count(),
                          df.loc[df.B=='a',"A"].sum()]],
                          columns=['A_count_all','A_sum_all','A_count_a','A_sum_a']))

   A_count_all  A_sum_all  A_count_a  A_sum_a
0            5         15          3        8
</code></pre>

python pandas dataframe group-by sum