One hot encode categorical features

Imports

import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder

Create data

d = {'fruit': ['apple', 'pear', 'apple', 'pear', 'pear']}
df = pd.DataFrame(d)
df

fruit
0 apple
1 pear
2 apple
3 pear
4 pear

Initialise

one_hot = OneHotEncoder()

Train

one_hot.fit(df)
OneHotEncoder(categorical_features=None, categories=None, drop=None,
              dtype=<class 'numpy.float64'>, handle_unknown='error',
              n_values=None, sparse=True)

Apply

one_hot.transform(df)
<5x2 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>

View

one_hot.transform(df).toarray()
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.],
       [0., 1.]])

Option 2 (pd.get_dummies)

pd.get_dummies(df['fruit'])

apple pear
0 1 0
1 0 1
2 1 0
3 0 1
4 0 1