title: Create a binary matrix from 2 dataframe columns in Python
body: <p>I need to create a binary matrix</p>
  
  <p>Example Data in a pandas DataFrame</p>
  
  <pre><code>ID P
  2  1
  1  2
  3  2
  1  3
  1  4
  2  5
  3  5
  </code></pre>
  
  <p>Using </p>
  
  <pre><code>A = pd.DataFrame(index=df.ID.values, columns=df.P.values, 
                         data=(df.P.values == df.P.values[:,None]).astype(int))
  </code></pre>
  
  <p>My current output</p>
  
  <p><a href="https://i.stack.imgur.com/AujQ9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AujQ9.png" alt="Current Output"></a></p>
  
  <p>Which is correct in terms of where the '1's' hit, but I just want to have the column / row numbers consolidated and the row numbers in order as in:</p>
  
  <pre><code>index 1 2 3 4 5 6 7
  1     0 1 1 1 0 1 0
  2     1 0 0 0 1 0 1
  3     0 1 0 1 1 1 0
  </code></pre>
  
  <p>If that's not clear, feel free to question!</p>