transform string column of a pandas data frame into 0 1 vectors
<p><code>LabelEncoder</code> and <code>OneHotEncoder</code> works pretty good for numpy array, which transform string into <code>0,1</code> based vectors.</p>

<p>My question is, is there a neat API to convert a column of a pandas data frame into <code>0, 1</code> vectors? I showed my code and raw content of the pandas data frame <code>123.csv</code>, suppose I want to binary <code>0, 1</code> for columns <code>c_a</code>,<code>c_b</code>,<code>c_c</code>, each of the 3 columns are independent, I want to binary <code>0, 1</code> for the separately independent.</p>

<p>Code,</p>

<pre><code>import pandas as pd
sample=pd.read_csv('123.csv', sep=',',header=None)
print sample.dtypes
</code></pre>

<p>123.csv content,</p>

<pre><code>c_a,c_b,c_c,c_d
hello,python,pandas,1.2
hi,c++,vector,1.2
</code></pre>

<p>Label Encoder and OneHotEncoder examples for numpy,</p>

<pre><code>from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

S = np.array(['b','a','c'])
le = LabelEncoder()
S = le.fit_transform(S)
print(S)
ohe = OneHotEncoder()
one_hot = ohe.fit_transform(S.reshape(-1,1)).toarray()
print(one_hot)
which results in:

[1 0 2]

[[ 0.  1.  0.]
 [ 1.  0.  0.]
 [ 0.  0.  1.]]
</code></pre>

<p><strong>Edit 1</strong>, tried <code>get_dummies</code>, and it seems results are <code>0.0</code> and <code>1.0</code> (seems <code>float</code>), is there a way to convert into integer directly?</p>

<pre><code>   0_c_a  0_hello  0_hi  0_ho  1_c++  1_c_b  1_java  1_python  2_c_c  2_numpy  \
0    1.0      0.0   0.0   0.0    0.0    1.0     0.0       0.0    1.0      0.0   
1    0.0      1.0   0.0   0.0    0.0    0.0     0.0       1.0    0.0      0.0   
2    0.0      0.0   1.0   0.0    0.0    0.0     1.0       0.0    0.0      0.0   
3    0.0      0.0   0.0   1.0    1.0    0.0     0.0       0.0    0.0      1.0  
</code></pre>

<p>Are you looking for <code>get_dummies</code>?</p>

<pre><code>s = pd.Series(["a", "b", "a", "c"])
pd.get_dummies(s)
</code></pre>

<p>If you want <code>ints</code>:</p>

<pre><code>pd.get_dummies(s).astype(np.uint8)
</code></pre>

<p>reference:</p>

<p><a href="http://stackoverflow.com/questions/27468892/pandas-get-dummies-to-output-dtype-integer-bool-instead-of-float">Pandas get_dummies to output dtype integer/bool instead of float</a></p>

python python-2.7 pandas numpy one-hot-encoding