title: Dynamically filtering a pandas dataframe
body: <p>I am trying to filter a pandas data frame using thresholds for three columns</p>
  
  <pre><code>import pandas as pd
  df = pd.DataFrame({"A" : [6, 2, 10, -5, 3],
                     "B" : [2, 5, 3, 2, 6],
                     "C" : [-5, 2, 1, 8, 2]})
  df = df.loc[(df.A &gt; 0) &amp; (df.B &gt; 2) &amp; (df.C &gt; -1)].reset_index(drop = True)
  
  df
      A  B  C
  0   2  5  2
  1  10  3  1
  2   3  6  2
  </code></pre>
  
  <p>However, I want to do this inside a function where the names of the columns and their thresholds are given to me in a dictionary. Here's my first try that works ok. Essentially I am putting the filter inside <code>cond</code> variable and just run it: </p>
  
  <pre><code>df = pd.DataFrame({"A" : [6, 2, 10, -5, 3],
                     "B" : [2, 5, 3, 2, 6],
                     "C" : [-5, 2, 1, 8, 2]})
  limits_dic = {"A" : 0, "B" : 2, "C" : -1}
  cond = "df = df.loc["
  for key in limits_dic.keys():
      cond += "(df." + key + " &gt; " + str(limits_dic[key])+ ") &amp; "
  cond = cond[:-2] + "].reset_index(drop = True)"
  exec(cond)
  df
      A  B  C
  0   2  5  2
  1  10  3  1
  2   3  6  2
  </code></pre>
  
  <p>Now, finally I put everything inside a function and it stops working (perhaps <code>exec</code> function does not like to be used inside a function!):</p>
  
  <pre><code>df = pd.DataFrame({"A" : [6, 2, 10, -5, 3],
                     "B" : [2, 5, 3, 2, 6],
                     "C" : [-5, 2, 1, 8, 2]})
  limits_dic = {"A" : 0, "B" : 2, "C" : -1}
  def filtering(df, limits_dic):
      cond = "df = df.loc["
      for key in limits_dic.keys():
          cond += "(df." + key + " &gt; " + str(limits_dic[key])+ ") &amp; "
      cond = cond[:-2] + "].reset_index(drop = True)"
      exec(cond)
      return(df)
  
  df = filtering(df, limits_dic)
  df
      A  B  C
  0   6  2 -5
  1   2  5  2
  2  10  3  1
  3  -5  2  8
  4   3  6  2
  </code></pre>
  
  <p>I know that <code>exec</code> function acts differently when used inside a function but was not sure how to address the problem. Also, I am wondering there must be a more elegant way to define a function to do the filtering given two input: 1)<code>df</code> and 2)<code>limits_dic = {"A" : 0, "B" : 2, "C" : -1}</code>. I would appreciate any thoughts on this.</p>