Having issue summarising python dataframe to one line per record
<p>I've got a dataframe in the form:</p>

<pre><code>df = pd.DataFrame({'id':['a', 'a', 'a', 'b','b'],'var':[1,2,3,5,9]})
</code></pre>

<p>and I'm trying to reshape it so that there is one line per 'id' and the values 'var' are displayed across in one line, so 'a' would have 1,2,3 ... 'b' would have '5,9'</p>

<p>I've tried with:</p>

<pre><code>test = pd.crosstab(df.id, df.var)  # but it does not work?
</code></pre>

<p>If someone could help me it would be much appreciated</p>

<p>EDIT, I enclose the desired results as a picture here<a href="http://i.stack.imgur.com/NgHBm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NgHBm.jpg" alt="enter image description here"></a></p>

<p><strong>UPDATE:</strong></p>

<pre><code>In [32]: df.groupby('id')['var'].apply(lambda x: x.astype(str).str.cat(sep=',')).reset_index()
Out[32]:
  id    var
0  a  1,2,3
1  b    5,9
</code></pre>

<p>or having <code>var</code> as a list:</p>

<pre><code>In [29]: df.groupby('id')['var'].apply(list).reset_index()
Out[29]:
  id        var
0  a  [1, 2, 3]
1  b     [5, 9]
</code></pre>

<p><strong>OLD answer:</strong></p>

<p>IIUC you can use <code>pivot_table()</code> which is used by <code>crosstab()</code> method internally?</p>

<pre><code>In [26]: df.pivot_table(index='id', columns='var', aggfunc='size', fill_value=0)
Out[26]:
var  1  2  3  5  9
id
a    1  1  1  0  0
b    0  0  0  1  1
</code></pre>

python pandas dataframe pivot-table