how to pivot complex dataframe
<p>I have a dataframe shown in below.</p>

<pre><code>df =pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'contract1' :["A", "B", "C", "D", "B"],
           'contract2' :["C", "A", np.nan, "A", np.nan],
           'contract3' :[np.nan, "C", np.nan, np.nan, np.nan] })
df

ID        contract1   contract2   contract3    
1             A           C         nan
2             B           A          C
3             C          nan        nan
4             D           A         nan
5             B          nan        nan
</code></pre>

<p>I would like the flag result like this;</p>

<pre><code>ID     A     B     C      D
1      1     0     1      0
2      1     1     1      0 
3      0     0     1      0
4      1     0     0      1
5      0     1     0      0  
</code></pre>

<p>This flag table show whether each ID have a each contract. 
Maybe pivot is available,but I couldn't handle this kind of complex dataframe...
Can I ask how to transform ?</p>

<p>A Faster implementation would be to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow"><code>str.get_dummies</code></a> as shown:</p>

<pre><code>pd.melt(df, id_vars=['ID']).set_index('ID')['value']        \
                           .str.get_dummies()               \
                           .groupby(level=0)                \
                           .agg(np.sum)

    A  B  C  D
ID            
1   1  0  1  0
2   1  1  1  0
3   0  0  1  0
4   1  0  0  1
5   0  1  0  0
</code></pre>

python pandas dataframe