Create two aggregate columns by Group By Pandas
<p>I'm new to DataFrames and I want to group multiple columns and then sum and keep a count on the last column. e.g.</p>

<pre><code>s = pd.DataFrame(np.matrix([[1, 2,3,4], [3, 4,7,6],[3,4,5,6],[1,2,3,7]]), columns=['a', 'b', 'c', 'd'])

   a  b  c  d
0  1  2  3  4
1  3  4  7  6
2  3  4  5  6
3  1  2  3  7
</code></pre>

<p>I want to group on <code>a</code>, <code>b</code> and <code>c</code> but then sum on <code>d</code> and count the elements within the group. 
I can count by </p>

<pre><code>s = s.groupby(by=["a", "b", "c"])["d"].count()

    a  b  c
    1  2  3    2
    3  4  5    1
          7    1
</code></pre>

<p>And I can sum by</p>

<pre><code>s = s.groupby(by=["a", "b", "c"])["d"].sum()

a  b  c
1  2  3    11
3  4  5     6
      7     6
</code></pre>

<p>However I want to combine it such that The resulting dataframe has both the sum and count columns. </p>

<pre><code>    a  b  c   sum    count
    1  2  3    11     2
    3  4  5     6     1
          7     6     1
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a>, or shorter version <code>agg</code>:</p>

<pre><code>print (s.groupby(by=["a", "b", "c"])["d"].agg([sum, 'count']))
#print (s.groupby(by=["a", "b", "c"])["d"].aggregate([sum, 'count']))
       sum  count
a b c            
1 2 3   11      2
3 4 5    6      1
    7    6      1
</code></pre>

<p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once" rel="nofollow">Pandas documentation</a>.</p>

<p><a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1822/grouping-data/6874/aggregating-by-size-and-count#t=201609091024047214605">Differences between size and count</a></p>

<p>If need count <code>NaN</code> values also:</p>

<pre><code>print (s.groupby(by=["a", "b", "c"])["d"].agg([sum, 'size']))
       sum  size
a b c           
1 2 3   11     2
3 4 5    6     1
    7    6     1
</code></pre>

python pandas dataframe group-by aggregate-functions