How to pivot pandas DataFrame column to create binary "value table"?
<p>I have the following pandas dataframe:</p>

<pre><code>import pandas as pd
df = pd.read_csv("filename.csv")

df 
     A   B         C         D        E    
0    a  0.469112 -0.282863 -1.509059  cat  
1    c -1.135632  1.212112 -0.173215  dog   
2    e  0.119209 -1.044236 -0.861849  dog   
3    f -2.104569 -0.494929  1.071804  bird   
4    g -2.224569 -0.724929  2.234213  elephant
...
</code></pre>

<p>I would like to create more columns based on the identity of categorical values in <code>column E</code> such that the dataframe looks like this:</p>

<pre><code> df 
         A   B         C         D        cat    dog     bird    elephant ....    
    0    a  0.469112 -0.282863 -1.509059  -1      0       0       0
    1    c -1.135632  1.212112 -0.173215   0     -1       0       0
    2    e  0.119209 -1.044236 -0.861849   0     -1       0       0
    3    f -2.104569 -0.494929  1.071804   0      0      -1       0
    4    g -2.224569 -0.724929  2.234213   0      0       0       0
    ...
</code></pre>

<p>That is, I pivot the values for column <code>E</code> to be a binary matrix based on the values of <code>E</code>, giving <code>1</code> if the value exists, and <code>0</code> for all others where it doesn't (here, I would like it to be <code>-1</code> or a "negative binary matrix")? </p>

<p>I'm not sure which function in pandas best does this: maybe <code>pandas.DataFrame.unstack()</code>? </p>

<p>Any insight appreciated!</p>

<p>use <code>pd.concat</code>, <code>drop</code>, and <code>get_dummies</code></p>

<pre><code>pd.concat([df.drop('E', 1), pd.get_dummies(df.E).mul(-1)], axis=1)
</code></pre>

<p><a href="http://i.stack.imgur.com/4kxQD.png" rel="nofollow"><img src="http://i.stack.imgur.com/4kxQD.png" alt="enter image description here"></a></p>

python pandas dataframe binary categorical-data