How would you improve and optimize a manual encoding like this?
The easiest and most efficient way to do it, is to use the One Hot Encoding ScikitLearn

This is an example:

&gt;&gt;&gt; from sklearn.preprocessing import OneHotEncoder
&gt;&gt;&gt; enc = OneHotEncoder()
&gt;&gt;&gt; enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])  
OneHotEncoder(categorical_features='all', dtype=&lt;... 'numpy.float64'&gt;,
       handle_unknown='error', n_values='auto', sparse=True)
&gt;&gt;&gt; enc.n_values_
array([2, 3, 4])
&gt;&gt;&gt; enc.feature_indices_
array([0, 2, 5, 9])
&gt;&gt;&gt; enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])