Python pandas group by two columns
<p>I have a pandas dataframe:</p>

<pre><code>       code   type
index  
  312   11     21
  312   11     41 
  312   11     21
  313   23     22
  313   11     21
  ...   ...    
</code></pre>

<p>So I need to group it by count of pairs 'code' and 'type' columns for each index item:</p>

<pre><code>        11_21   11_41  23_22
index  
  312       2      1      0
  313       1      0      1
  ...   ...   
</code></pre>

<p>How implement it with python and pandas?</p>

<p>Here's one way using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>pd.crosstab</code></a> and then rename column names, using levels information.</p>

<pre><code>In [136]: dff = pd.crosstab(df['index'], [df['code'], df['type']])

In [137]: dff
Out[137]:
code  11    23
type  21 41 22
index
312    2  1  0
313    1  0  1

In [138]: dff.columns = ['%s_%s' % c for c in dff.columns]

In [139]: dff
Out[139]:
       11_21  11_41  23_22
index
312        2      1      0
313        1      0      1
</code></pre>

<p><em>Alternatively, less elegantly,</em> create another column and use crosstab.</p>

<pre><code>In [140]: df['ct'] = df.code.astype(str) + '_' + df.type.astype(str)

In [141]: df
Out[141]:
   index  code  type     ct
0    312    11    21  11_21
1    312    11    41  11_41
2    312    11    21  11_21
3    313    23    22  23_22
4    313    11    21  11_21

In [142]: pd.crosstab(df['index'], df['ct'])
Out[142]:
ct     11_21  11_41  23_22
index
312        2      1      0
313        1      0      1
</code></pre>

python pandas dataframe group-by