title: One-hot encode pandas dataframe using dictionary with column name and values
body: <p>I currently have the below code to one-hot encode a pandas dataframe using a dictionary where keys are feature names and values are list of values for the feature.</p>
  
  <pre><code>def dummy_encode_dataframe(self, df, dummy_values_dict):
      for (feature, dummy_values) in sorted(dummy_values_dict.items()):
          for dummy_value in sorted(dummy_values):
              dummy_name = u'%s_%s' % (feature, dummy_value)
              df[dummy_name] = (df[feature] == dummy_value).astype(float)
          del df[feature]
      return df
  </code></pre>
  
  <p>The <code>dummy_values_dict</code> has the structure:</p>
  
  <pre><code>feature name (key)   list of possible values (strings)
  ---------            ---------------------------------
  F1                   ['A', 'B', 'C', 'MISSING']
  F2                   ['D', 'E', 'F', 'MISSING']
  F3                   ['G', 'H', 'I']
  </code></pre>
  
  <p>with sample input/output:</p>
  
  <pre><code>df (one row):
  ====
  F1     F2    F3
  ---  -----  -----  
  'A'    'Q'   'H'
  </code></pre>
  
  <p>expected output:</p>
  
  <pre><code>df_output:
  ====
  F1_A  F1_B  F1_C  F1_MISSING F2_D  F2_E  F2_F F2_MISSING F3_G  F3_H  F3_I
  ---   ----  -----  --------- ----  ----  ---- ---------- ----  ----  -----
   1      0     0       0        0    0     0        0       0     1    0
  </code></pre>
  
  <p>The problem is that the for-loops takes too long to run. Any way to optimize it?</p>
  
  <p><strong>UPDATE 1:</strong> From the comment about using OneHotEncoder in scikit-learn...
  Can you elaborate on this piece of code to get the desired output?</p>
  
  <pre><code>import pandas as pd 
  df = pd.DataFrame(columns=['F1', 'F2', 'F3']) 
  df.loc[0] = ['A', 'Q', 'H'] 
  dummy_values_dict = { 'F1': ['A', 'B', 'C', 'MISSING'], 'F2': ['D', 'E', 'F', 'MISSING'], 'F3': ['G', 'H', 'I'] } 
  # import OneHotEncoder 
  from sklearn.preprocessing import OneHotEncoder 
  categorical_cols = sorted(dummy_values_dict.keys()) 
  # instantiate OneHotEncoder 
  # todo: encoding...
  </code></pre>