get both unique count and max in group-by of pandas dataframe
<p>Using Pandas data frame group by feature and I want to group by column <code>c_b</code> and (1) calculate unique count for column <code>c_a</code> and column <code>c_c</code>, (2) and get the max value of column c_d. Wondering if there is any solution to write one line of group by code to achieve both goals? I tried the following line of code, but it seems not correct.</p>

<pre><code>sampleGroup = sample.groupby('c_b')(['c_a', 'c_d'].agg(pd.Series.nunique), ['c_d'].agg(pd.Series.max))
</code></pre>

<p>My expected results are,</p>

<p><strong>Expected results</strong>,</p>

<pre><code>c_b,c_a_unique_count,c_c_unique_count,c_d_max
python,2,2,1.0
c++,2,2,0.0
</code></pre>

<p>Thanks.</p>

<p><strong>Input file</strong>,</p>

<pre><code>c_a,c_b,c_c,c_d
hello,python,numpy,0.0
hi,python,pandas,1.0
ho,c++,vector,0.0
ho,c++,std,0.0
go,c++,std,0.0
</code></pre>

<p><strong>Source code</strong>,</p>

<pre><code>sample = pd.read_csv('123.csv', header=None, skiprows=1,
    dtype={0:str, 1:str, 2:str, 3:float})
sample.columns = pd.Index(data=['c_a', 'c_b', 'c_c', 'c_d'])
sample['c_d'] = sample['c_d'].astype('int64')
sampleGroup = sample.groupby('c_b')(['c_a', 'c_d'].agg(pd.Series.nunique), ['c_d'].agg(pd.Series.max))
results.to_csv(sampleGroup, index= False)
</code></pre>

<p>You can pass a dict to <code>agg()</code>:</p>

<pre><code>df.groupby('c_b').agg({'c_a':'nunique', 'c_c':'nunique', 'c_d':'max'})
</code></pre>

<p>If you don't want <code>c_b</code> as index, you can pass <code>as_index=False</code> to <code>groupby</code>:</p>

<pre><code>df.groupby('c_b', as_index=False).agg({'c_a':'nunique', 'c_c':'nunique', 'c_d':'max'})
</code></pre>

python python-2.7 pandas dataframe group-by