Python Pandas group by function
<p>I have this table </p>

<pre><code>    uname   sid usage
0   Ahmad   a   5
1   Ahmad   a   7
2   Ahmad   a   10
3   Ahmad   b   2
4   Mohamad c   6
5   Mohamad c   7
6   Mohamad c   9
</code></pre>

<p>I want to group by uname and side, and have usage column =  <code>group.max</code> - <code>group.min</code>. But if group count is <code>1</code> return group <code>max</code> </p>

<p>the out put should be </p>

<pre><code>    uname   sid usage
0   Ahmad   a   5
1   Ahmad   b   2
2   Mohamad c   3    
</code></pre>

<p>First, use <code>agg</code> to grab <code>min</code>, <code>max</code>, and <code>size</code> of each group.<br>
Then multiply <code>min</code> by <code>size &gt; 1</code>.  When it is, it will equal <code>min</code>, else <code>0</code>.  Then subtract that from <code>max</code>.</p>

<pre><code>d1 = df.groupby(['uname', 'sid']).usage.agg(['min', 'max', 'size'])
d1['max'].sub(d1['min'].mul(d1['size'].gt(1))).reset_index(name='usage')
</code></pre>

<p><a href="http://i.stack.imgur.com/jIDZN.png" rel="nofollow"><img src="http://i.stack.imgur.com/jIDZN.png" alt="enter image description here"></a></p>

python pandas group-by max min