Calc value count in few columns of DataFrame (Pandas Python)
<p>I have a dataFrame: </p>

<pre><code>   id   code_1   code_2
0  11    1451     ffx
1  15    2233     ffx 
2  24    1451     mmg
3  15    1451     ffx 
</code></pre>

<p>I need get number of each code value (for all code_1 values and all code_2 values) for unique id. For example:</p>

<pre><code>   id   1451   2233   ...   ffx  mmg   ...
0  11    1       0    ...    1    0    ...
1  15    1       1    ...    2    0    ...
2  24    1       0    ...    0    1    ...
</code></pre>

<p>I do this code:</p>

<pre><code>y = data.groupby('id')
        .apply(lambda x: x[['code_1', 'code_2']].unstack().value_counts()) 
        .unstack()
</code></pre>

<p>But i think that something wrong because number of result table columns less then number of varians code_1 and code_2.</p>

<p>Consider merging pivot_tables using the aggfunc <em>len</em> for counts.</p>

<pre><code>from io import StringIO
import pandas as pd

data = '''
id   code_1   code_2
11    1451     ffx
15    2233     ffx 
24    1451     mmg
15    1451     ffx'''

df = pd.read_table(StringIO(data), sep="\s+")

df = pd.merge(df[['id', 'code_1']].pivot_table(index='id', columns='code_1', aggfunc=len).\
                                               reset_index(drop=True),
              df[['id', 'code_2']].pivot_table(index='id', columns='code_2', aggfunc=len).\
                                               reset_index(drop=True),
              left_index=True, right_index=True).fillna(0)

#    1451  2233  ffx  mmg
# 0   1.0   0.0  1.0  0.0
# 1   1.0   1.0  2.0  0.0
# 2   1.0   0.0  0.0  1.0
</code></pre>

python pandas dataframe