Pandas group and record grouped values
<p>I have the following dataset:</p>

<pre><code>Code    Value
100004  1
1017    1
1017    3
1071    1
1071    3
3039    1
3397    1
3397    3
</code></pre>

<p>I was able to count the Value using pandasDataFrame.groupby('Code', as_index=False).agg('count')</p>

<p>I would like to count and in the same time to record the values in a new column. I want the result to look like the example bellow</p>

<pre><code>Code       NoValues      Values
100004     1             1
1017       2             1,3
1071       2             1,3
3039       1             1
3397       2             1,3
</code></pre>

<p>Is it possible to do it with pandas?</p>

<p>You can use <code>groupby</code> + <code>agg</code>:</p>

<pre><code>df.Value.groupby(df.Code).agg({'Values': lambda g: list(g), 'NumValues': lambda g: len(g)}).reset_index()
</code></pre>

<p>For example:</p>

<pre><code>df = pd.DataFrame({'Code': [1004, 1004, 1007], 'Value': [1, 2, 8]})
&gt;&gt;&gt; df.Value.groupby(df.Code).agg({'Values': lambda g: list(g), 'NumValues': lambda g: len(g)}).reset_index()
    Code    NumValues   Values
0   1004    2   [1, 2]
1   1007    1   [3]
</code></pre>

python pandas