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>We could also do this with <code>melt/pivot_table</code></p>

<pre><code>res = pd.melt(df, id_vars = ['ID'], value_vars = ['contract1', 
       'contract2', 'contract3']).pivot_table(index = 'ID', 
          columns = 'value', fill_value = 0, aggfunc=len)
print(res)
#    variable         
#value        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>

<h3>data</h3>

<pre><code>import pandas as pd;
import numpy as np;
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
</code></pre>

python pandas dataframe