title: Pandas `try df.loc[x]` vs `x in df.index`
body: <p>I have a dataframe with one column. I would like to write a function that returns the column value for a given key value; or a different (constant) value if the key is not in the index. I can think of (at least) two reasonable ways to implement this -- <strong>aside from speed is there a reason one would be better than the other?</strong></p>
  
  <p>And w/r/t speed, with len(df) = 10k and len(ids_to_check) = 20k, the try/except is about 2x slower. This is surprising to me since the other method has to traverse the index twice. <strong>Any intuitive explanation for this behavior?</strong></p>
  
  <ol>
  <li><p>Using a <code>try</code>/<code>except</code> block</p>
  
  <pre><code>def attempt_1(id_val,df):
      try:
          return df.loc[id_val]
      except KeyError:
          return constant_val
  
  %timeit [attempt_1(i,df) for i in ids_to_check]
  
  1 loops, best of 3: 480 ms per loop
  </code></pre></li>
  <li><p>Using <code>in</code> to test if <code>id_val</code> is in the index</p>
  
  <pre><code>def attempt_2(id_val,df):
      if id_val in df.index:
          return df.loc[id_val]
      else:
          return constant_val
  
  %timeit [attempt_2(i,df) for i in ids_to_check]
  
  1 loops, best of 3: 235 ms per loop
  </code></pre></li>
  </ol>