Faced problem while applying OneHotEncoder For classification, I was trying to convert categorical data into numeric by applying OneHotEncoder. But it shows error could not convert string to float

Here is the sample of my categorical data set and code of One Hot Encoding.



# TODO: create a OneHotEncoder object, and fit it to all of X
from sklearn.preprocessing import OneHotEncoder

# 1. INSTANTIATE
enc = OneHotEncoder()

# 2. FIT
enc.fit(train_obj)

# 3. Transform
train_ = enc.transform(train_obj)
train_.head()

And error message:


I couldn't understand what's the problem &amp; how could I solve it.

If I apply get_dummies() method, is it similar of OneHotEncoder ?
Consider the following demo:

Source DF:

In [53]: df
Out[53]:
   A          B                   C
0  1  Bachelors  Married-civ-spouse
1  2    HS-grad            Divorsed
2  3       11th  Married-civ-spouse


Option 1:

In [54]: for c in df.columns[df.dtypes.eq('object')]:
    ...:     df = df.join(df[c].str.get_dummies())
    ...:


Result:

In [55]: df
Out[55]:
   A          B                   C  11th  Bachelors  HS-grad  Divorsed  Married-civ-spouse
0  1  Bachelors  Married-civ-spouse     0          1        0         0                   1
1  2    HS-grad            Divorsed     0          0        1         1                   0
2  3       11th  Married-civ-spouse     1          0        0         0                   1


Option 2:

In [58]: df = df.join(pd.get_dummies(df.select_dtypes(['object'])))

In [59]: df
Out[59]:
   A          B                   C  B_11th  B_Bachelors  B_HS-grad  C_Divorsed  C_Married-civ-spouse
0  1  Bachelors  Married-civ-spouse       0            1          0           0                     1
1  2    HS-grad            Divorsed       0            0          1           1                     0
2  3       11th  Married-civ-spouse       1            0          0           0                     1